What is a Closure in JavaScript?JavaScript Basics
Understanding Closures: A Deep Dive into Scopes and Variable Accessibility in JavaScript
A closure in JavaScript is a concept where an inner function has access to its own variables, the variables of the outer function, and global variables, even after the outer function has finished executing. This means that a closure can remember and access variables from its parent scope (the outer function), even after the parent function has finished executing.
Here’s a breakdown:
- Inner Function: The function defined inside another function.
- Outer Function: The function that contains the inner function.
- Parent Scope: The scope of the outer function, from where the inner function can access variables.
- Global Variables: Variables that are defined outside any function and can be accessed from any function in the file.
Example:
function outerFunction(outerVariable) {
let outerLocalVariable = 'I am outside!';
function innerFunction(innerVariable) {
// innerFunction is the closure and has access to all variables listed below.
console.log(innerVariable); // Inner Scope
console.log(outerLocalVariable); // Outer Scope
console.log(outerVariable); // Outer Scope
console.log(globalVariable); // Global Scope
}
return innerFunction;
}
let globalVariable = 'I am Global!';
let closureInstance = outerFunction('I am from Outer!');
closureInstance('I am from Inner!');
In this example:
innerFunction
is the inner function.outerFunction
is the outer function.- When calling
outerFunction
, it returns theinnerFunction
, preserving the outer scope. Therefore,closureInstance
is, in essence, theinnerFunction
, but it still has access to the variables in theouterFunction
scope, even afterouterFunction
has finished executing. - When we call
closureInstance('I am from Inner!')
, it is equivalent to callinginnerFunction
with access to the variables fromouterFunction
and the global scope.
Output of the Example:
I am from Inner!
I am outside!
I am from Outer!
I am Global!
Explanation
Think of closures like backpacks. Imagine the outer function is going to a camp, and the inner function is what it brings back. The inner function brings a backpack (closure) with it, filled with all the skills (variables) it learned at the camp (outer function), and it can use those skills (variables) whenever it wants, even after the camp (outer function) is over. So, the backpack (closure) allows the inner function to remember and use the skills (variables) from the camp (outer function) anywhere it goes!