Def: A closure is a function having access to the parent scope, even after the parent function has closed.
I know, its confusing to understand JS closures; I will try to explain below in as simple terms as I can;
Remember:
- Aim of “closures” is to create access to ‘private’ variables of a function, even after that function is closed.
- Immediately Invoking function only runs once.
Steps to create closure: (Counter Function)
- Write a increment function which returns count = count +1;
function(){ return count = count +1; } - Write an anonymous function which returns above function; also initialize counter here;
function (){var counter = 0;return function(){return count = count +1;}} - Create an immediately invoking functiona. start with ()();
b. Put above function into first braces;(function (){var counter = 0;return function(){return count = count +1;}})();
- Assign this immediately invoking function to a variable & Done.>!!! Here, the final code would look like;
var add = (function () {var counter = 0;return function () {return counter += 1;}})();add();
add();Result : 2
Let’s understand it now;
- As stated above, IIF only runs once; therefore counter gets initialized once; no matter how many times you call the function. Here the variable is ‘private‘, means it can only be changed by methods within that function.
- For the inner function; that variable is accessible & in the return statement its value gets incremented by 1, every time it gets called. Here, the variable becomes ‘protected’ & not accessible for outside world.Wonderful..!! isn’t it?