What is Closure

A Closure is combination of function and the lexical environment (surrounding state). Using Closure, a nested function ( function inside another function) can access local variables of parent functions.

Closure are created every time a function is created inside another function. The child function can access variables of parent function. But parent function cannot access variables of child function because of scope.

Closure example

7


function outer(){
    var x=3;
    function inner(){
        var y=4;
        return x+y;
    }
    return inner;
}

console.log( outer()() )

In the above example, the function inner can access variables of outer.


Lexical Environment

Lexical Environment is the scope of function. A variable inside function is accessible anywhere in the function. When a nested function is created, it can also access variable of parent function.

Lexical Environment of function


function outer()
{
    var x=3;
    function inner(){
        var y=5;
        return x+y;
    }
}

Lexical Environment of inner function


function outer()
{
var x=3;
function inner(){
    var y=5;
    return x+y;
}
}

Closure Scope

Every Closure has three scopes.

  1. global
  2. parent function or block
  3. local scope

12


var x=3; // global

function outer(){
    var y=4;    // function

    function inner(){
        var z=5;    // local
        return x+y+z;
    }

    return inner;
}
console.log( outer()() )