Understanding closures in JavaScript

Kazi Minhajul Haider
2 min readMay 6, 2021

JavaScript closure is a powerful thing of JS. Now question is What did I mean by closure right ?

According to my understanding when you execute a function within a function a closure is created.

For example:

function add(){
let i = 0;
return function(){
return i++;
}
}

Look at the code above we have a function named add. This add() function have a local variable i. When we call this function this local variable is created and after returning from the function this variable completely abolished. And this add function return a anonymous function. This anonymous function returns value of i. i++ means post increment. It means it will return the value of i first then the value of i will be incremented.

Now if we call the add function, lets see what happens

let x = add(); //now x contains the anonymous function; lets call it
x(); //output 0 ;
x(); //output 1
x(); //output 2
x(); //output 3

Look, when we add() function it returns us the anonymous function. x holds the returned anonymous function. then we called the anonymous function it returns us 0, the value of i. Then the value of i incremented by 1 and stored in i. Now the value of i is 1. Then we called again and it returns the value of 1. This is the output coming.

But at the beginning I said you that when a function return the value its variables also closed or abolished. Then how the anonymous function is accessing the local variable of add function right ?
The answer is Closure saves the state of the outer or parent function variable but does not expose those variables. You would not able to access the value of “ i ” from outside this is called encapsulation in OOP.

Now if we call the add function again then

let y = add(); //now y contains the anonymous function; lets call it
y(); //output 0 ;
y(); //output 1

now look we called add() function again and add function returned a anonymous function and stored in y. Then we called y() and we got 0.
But look at the upper code snippet that when we called x for the last time the value of x was 5. I means that every time we call a closure it will create a new private variable and only using the anonymous you can manipulate the value of i. Which is very powerful.

I hope you get a overall introductory idea of javaScript closure. For better understanding you can see that js dude’s article on scope and closure. I understand this topic from there and shared my uderstanding. Thank you

--

--