Closures are among the most important and most frequently asked concepts in JavaScript interviews.
In this article, you will learn about closure in JavaScript. As a beginner, closures may feel a little complex at first, but don't worry—we will learn them in an easy and straightforward way.
What is Closure
A closure is a function that is bundled together with its lexical environment.
In simple words,
A closure allows an inner function to access variables from an outer function even after the outer function has finished executing.
Let's see with the small example :
function Outer() {
var x = 10 ;
function Inner(){
console.log(x); // 10
}
return Inner;
}
const closure = Outer();
closure();
Explanation
The variable X is declared inside the Outer function.
The Inner function uses the variable X.
When Outer() is called , it's return the Inner function.
Even after Outer() has finished executing , inner function still remember the value of X.
This is know as closure.
In this example, Inner() forms a closure because it remembers the variable X from its lexical scope, and it prints 10.
Lexical Scope
JavaScript uses lexical scoping, which means:
Let's see what happens when the same variable name exists in different lexical scopes.
Same variable in two different lexical scope
If we declare the same variable name inside the inner function, JavaScript will use the variable from the nearest scope.
for example :
function Outer() {
var x = 10 ;
function Inner(){
var x = 20;
console.log(x); // 20
}
return Inner;
}
const closure = Outer();
closure();
Explanation
Here, the variable X is declared in both the outer and inner functions.
Because of lexical scope , JavaScript first checks the current scope.
Since X exists inside the inner function, it uses that value.
The outer variable X is ignored in this case.
So, the output will be 20.
How Closures Work Behind the Scenes
Let’s take a look at what happens behind the scenes when closures are used:
Execution Context: When outer function is called, a new execution context is created with its own execution context (including variables and functions).
Inner Function Access: When inner function is returned, it still retains access to the outer function's variables even though the outer function has already finished executing.
Lexical Environment: This is stored as a lexical environment in the JavaScript engine, allowing the inner function to keep references to its outer variables, even after the outer function completes.
Conclusion
Closures are very powerful feature in JavaScript. Closures are an essential concept in JavaScript. Although they may seem complex initially, but consistent practice and hands-on examples make them easy to understand.
I hope this helps you!