Scopes and Closures in JavaScript
Programming #Javascript# Scopes

Scope.

Scope controls the visibility and lifetimes of variables and parameters. Most programming languages have block scope that is all variables defined in a block { ... } are not visible from the outside of the block. The good thing is variables defined in a block can be released when the execution of the block finished but unfortunately JavaScript doesn’t have block scope. JavaScript has 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.

around a minute read 9th Nov 2020

About

A entrepreneur, running an early stage venture, VizitDoc and a MVP-First Service Based Companay ThecodeWork.

A dreamer, having care for alternative education.

Archives - 1

  • Code

    20 Articles

    List of code snippet and articles I wrote when I started blogging in early 2016 😃

Codementor badge