Saturday, 3 March 2018

Difference between let and var in javascript

<script>
    //differnce between let and var in javascript

        function checkVarScope() {
            for (var i = 0; i < 5; i++) {

            }
            console.log(i);
        }

        function checkLetScope() {
            for (let i = 0; i < 5; i++) {
                console.log(i);
            }
            //console.log(i); //throw error i is not defined
        }

        $(document).ready(function () {
           //Initialisation
            let a=100;
            //let a=200; //do not reinitialize again
            var b = 50;
            var b = 60; //reinitialize again and again
            var b = 70;
            //console.log(b);

            //scope-
            checkVarScope(); //in var value is available to the function scope till function(){}.
            checkLetScope(); //in let value is available to the block scope means till for(){}.

            //hoisting
            (function () {
                a = 10;
                console.log(a); //10
                var a;
            })();

            (function () {
                b = 11; //throw error let do not give hoisting feature in javascript
                console.log(b);
                let b;
            })();
        });
</script>

No comments:

Post a Comment