Scopes and Closures in JavaScript

Scope

Scope controls the visibility and lifetimes of variable and parameters. Most programing languages have block scope that is all variables defined in a block { ... } are not visible from outside of the block.
The good thing is variables defined in a block can be released when execution of the block finished but unfortunately JavaScript doesn’t have block scope. JavaScript have function scope that means, the parameters and the variables defined in a function are not visible outside of the function, and that variable defined within a function is visible everywhere within the function.

A Basic Example of Scopes in JavaScript:


var foo = function(){
    var a = 3, b = 5;

    var bar = function(){
        var b = 7, c = 11;

        /**
        * At this point of time
        * a = 3
        * b = 7
        * c = 11
        */

        a += b + c;

        /**
        * At this point of time
        * a = 21
        * b = 7
        * c = 11
        */
    }
    /**
    * At this point of time
    * a = 3
    * b = 5
    * c = 'undefined'
    */
    bar();

    /**
    * At this point of time
    * a = 21
    * b = 5
    * c = 'undefined'
    */
}

Closure

Closures allow JavaScript programmers to write better code. Creative, expressive, and concise. As we know about the JavaScript’s scope that inner functions get access to the parameters and the variables of the functions they are defined within. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly. You create a closure by adding a function inside another function.

A Basic Example of Closures in JavaScript:


var myObject = function(){
    var value = 0;

    return {
        increment: function(inc){
            value += typeof inc === 'number' ? inc : 1;
        },
        getValue: function(){
            return value;
        }
    };
}();

We are not assigning a function to myObject. We are assigning the result of invoking that function. Notice that () on the last line. The function returns an object containing two methods, and those methods continue to enjoy the privilege of access to the value variable.