re: Explain Closures to me like I am five VIEW POST

FULL DISCUSSION
 

A 5 year old may not understand this unless he/she has an understanding of global variables.

Take this piece of code

var a = 0;

function increment() {
    a += 1;
}

function decrement() {
    a -= 1;
}

Both the functions can use the variable 'a' since its global. But what if you want to exclusively use it for one of the methods. How can you do that? Well closures make that possible. Its a global variable but only that function can access and write on it.

function addOne() {
    var a = 0;
    return function () {return a += 1;}
};
var increment = addOne();

increment() // after this a's value will be 1
increment() // a will be 2

Here 'a' is a global variable but only increment function has access to it. There is nothing more to closure.

code of conduct - report abuse