Closures what? When you are able to access a variable defined in a function scope even after the function exited is known as closure. Everyday in javascript we write hundreds of closure still many of the javascript developer doesn’t know about them. Shall we learn with an example?

function x () { 
var k = 10;
function add (b) {
return k+ b;
}
return add;
}
var q = x();
var sum = q(20);
console.log(sum); // it will output 30

See we are able to use k even when x is returned and executed. We defined a function named x inside the x we defined k and add. Inside add we returned k+ b. Then we defined q and stored the returned value of the x inside it. Then we executed q and stored its returned value inside sum and if we output sum 30 will be printed on our console because k= 10 and b = 20.

See these are the closure very easy and we already use them every day.

This is a drawback as well as a Benefit of Javascript, Javascript is so easy to learn and without knowing much of the internal of the language you are able to build amazing applications, but when a problem arises, you don’t have enough knowledge how javascript works internally and are not able to solve even most of the simpler problems.

Really loved this article ?

Please subscribe to my blog. You will receive articles like this one directly in your Inbox frequently.