Explaining JavaScript closures in one simple program. 3 minute read.
Geo Mukkath
Posted on December 8, 2022
Closures are nothing but functions plus it’s lexical scope.
Let’s look at an example to understand closures.
function outer(){
let a = 5;
function inner(){
console.log('inner', a);
}
inner();
}
outer();
//prints 'inner', 5
Here we have a function called outer.
We have an inner function called ‘inner’ which simply logs inner with a variable a.
The variable a is declared outside the inner function.
We call inner inside the outer function.
When we call the outer function it simply prints the log. That’s simple.
I’ve modified the code below. Now think of an answer.
function outer(){
let a = 5
function inner(){
console.log('inner', a);
}
return inner;
}
let y = outer();
y();
It prints the exact same thing.
I have declared a variable y which stores the outer function and I call y later.
Here when I return inner, the value that get stored in the variable y must only be inner.
How does it remember a ? a is outside inner, despite that it remembers a.
This is called closure. The closure of inner is the function itself + its lexical scope.
Posted on December 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.