Javascript Closure Explained

Tuesday, November 29, 2016

When we create the JavaScript function within another function and the inner function can access to all the variable of outer function.

How to create closure in javascript

Example 1:

function outerFunction(a) {
    var intial = 5;

    function innerFunction(b) {
        console.log(a + b + (++intial)); // It will return the 20.
    }
    innerFunction(10);
}

outerFunction(4); // Pass an argument 4

Output is 20

Check in jsfiddle

Here innerFunction() function can access to argument "a" and variable "intial", which are define in outerFunction() function.

Accessing variable outside of your scope create a closure.

Example 2:

function clickCounter() {
    var counter = 0;

    function runCounter() {
        return counter += 1;
    };

    return runCounter;
}

var counter = clickCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3

Check in jsfiddle

One important characteristic of closure is that outer variables can keep their states between multiple calls.

In the above example, outer function clickCounter returns the reference of inner function runCounter(). runCounter increases the outer variable counter to one. So calling inner function multiple time will increase the counter to one each time.

You Might Also Like

0 comments