Closures🤯 in JavaScript

Share

Many people are confused by the concept of closure in JavaScript. By the end of this blog, you’ll have a crystal clear understanding of it. So, let’s start!

Now, what is “Closure”? The closure is the combination of a function bundled together with references to its surrounding state blah…blah…blah. That’s what you see or hear on the internet.

Let’s have a function nested inside a function. The inner function can access the variable of the outer function, right? It’s obvious.  

function outer()
{
let a = 2;
function inner()
{
console.log(a);
}
}

Now, let’s return the “inner” function to use it outside the “outer” function.

function outer()
{
let a = 2;
function inner()
{
console.log(a);
}
return inner;
}
let result = outer(); // "outer" function execution is finished here
result(); // Displays 2

You should know that the returned function can be called from outside. But wait…the returned “inner” function displays the value of “a”. But, it’s being called from outside the scope of the “outer” function. Will, it still displays the value of “a”? Answer is YES!!!

It is possible because of Closure. The value of “a” is automatically stored in a Closure when creating the function. Think of it as a memory that stores all the variables of the “outer” function in a different memory space which is then used by the “inner” function to access those variables even though the “outer” function has finished executing. 

Note that even the argument of the “outer” function is stored in Closure as its variable. Hence, the “inner” function can access it from anywhere.

function outer(a)
{
function inner()
{
console.log(a);
}
return inner;
}
let result = outer(2); // "outer" function execution is finished here
result(); // Displays 2

What if the “inner” function is nested on deeper level? Can it still access the variable of the “outer” function? The answer is YES!!!

function outer()
{
let a = 2;
function new_function()
{
let b = 3;
function inner()
{
console.log(a + " " + b);
}
return inner;
}
return new_function(); //Executes new_function and returns "inner"
}
let result = outer(); //"outer" function execution is finished here
result(); //Displays 2 3

Share
%d bloggers like this: