Discuss Scoping In JavaScript.

scoping in JavaScript

JavaScript has lexical scoping based on functions but not blocks. Therefore:

//global scope
(function() {
    //anonymous function scope
    var foo = 1;
    function bar() {
        //bar function scope
        var foo = 2;
    }
    bar();
    console.log(foo); //outputs 1
    if(true) {
        var foo = 3; //redeclares foo
    }
    console.log(foo); //outputs 3
})();        

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *