Thursday, September 7, 2017

Javascript Closure | Simply Explained

In Javascript world the things are always confused. The most confused and made complicated feature is closure. But the truth is

Javascript Closure is really Simple

Let me start with the simple below javascript function

function simpleClosure(passed) {
   var inner = 20;
   return inner + passed;
}

simpleClosure(10);

The above function is the simple example for closure. 

When simpleClosure function executed, the passed(argument) value will be added in simpleClosure lexical scope.

Below code will give you better understanding.

var addTen = simpleClosure(10);
console.log(addTen); // Outputs 10

I am going to do the simple change in simpleClosure function. I moved passed argument variable to outer scope.

var passed = 10;
function simpleClosure() {
var inner = 20;
return inner + passed;
}
console.dir(simpleClosure);


Please go through the below output in the console, where you can see passed value 10 is under closure.



Lets see a bit complex closure, where inner function is involved.

function mediumClosure(passed) {
   return function () {
     var inner = 20;
     return inner + passed;
   }


var addTen = mediumClosure(10);

var addTwenty =  mediumClosure(20);
console.dir(addTen);
console.dir(addTwenty);

When i execute console.dir on addTen and addTwenty you can see the different closures created for two variables for the same function.




At the end what is closure in javascript?
"whenever you declare a function inside another function, the inside function(s) is/are recreated again each time the outside function is called" "Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created."

Functions preserves outer scope variable are closures.