What Are Closures in JavaScript?
Think of a closure like a backpack you carry with you after a class. Inside the backpack, you have all the notes and materials you learned during the class. Even after the class ends, you still have access to everything in your backpack whenever you need it. Similarly, a closure allows a function to keep access to the variables and parameters from its outer scope, even after that outer function has finished running and those variables are no longer accesssible outside of that function.
The explanation above is a typical way to describe closures, but is it beginner-friendly for someone new to JavaScript? Not really. I found it quite confusing when I first encountered it too. That's why I've written this article to make closures as simple as possible for anyone to understand. We'll begin by covering the basics before diving deeper into the topic.
Understanding Scope in JavaScript
To understand what closures is, we have to take a brief look at scope in JavaScript. Scope refers to the accessibility of variables and functions in different parts of our code. It determines where we can access certain variables or functions within our program.
There are two primary types of scope: global scope and local scope. Variables declared in the global scope exist outside of any function or block, making them accessible throughout the entire code. In contrast, variables declared in the local scope, such as within a function or block, are only accessible within that specific function or block. The code below illustrates this explanation.
// GLOBAL SCOPE
let myName = "John Doe";
function globalScope() {
console.log(myName);
}
globalScope(); //Output John Doe
console.log(myName); // Accessible here as well
// LOCAL SCOPE
function localScope() {
let age = 30;
console.log(age);
}
localScope(); //Output 30
console.log(age); //Output age is not defined (Not Accessible)
However, JavaScript uses a concept known as Lexical Scoping, which is crucial to understanding how closures work. Lexical Scoping means that the accessibility of variables is determined by the structure of our code at the time it is written. In simple terms, it’s like saying, "If a variable is declared inside a function, only that function and anything within it can access that variable."{https://javascript.info/closure}.
Lexical Scoping and Execution Context
To understand this more clearly, let's look at how JavaScript works behind the scenes. JavaScript uses something called an Execution Context, which is like a container that holds the code being run. It keeps track of variables, functions, and what part of the code is currently running. When a script starts, the Global Execution Context (GEC) is created. It’s important to note that there is only one Global Execution Context in a program.
The diagram above represents the Global Execution Context when our program begins. It consists of two phases: the Creation (or Memory) Phase and the Execution (or Code) Phase. In the Creation Phase, variables and functions are stored in memory—variables are initialized as undefined, and functions are fully stored. In the Execution Phase, JavaScript runs the code line by line, assigning values to variables and executing functions.
Now that we understand how JavaScript handles the execution context and lexical scoping, we can see how this directly ties into closures.
How Closures Work: An Example
A closure in JavaScript is created when an inner function retains access to the variables in its outer function's scope, even after the outer function has finished execution. This is possible because the inner function preserves the lexical environment it was defined in, allowing it to "remember" and use the variables from its outer scope.
Let’s look at the example below:
function outerFunction() {
let outerVariable = 'I am John Doe';
return function innerFunction() {
console.log(outerVariable);
};
}
const closureExample = outerFunction();
closureExample(); // Outputs: "I am John Doe"
Here is a guide on how the above code works. Whenever we call a function, the JavaScript engine creates a function execution context (FEC) specific to that function, which is created within the Global Execution Context (GEC). Unlike the GEC, there can be multiple FECs in a program. Each FEC goes through its own creation and execution phases and has its own variable and lexical environments. The lexical environment enables the function to access variables from its outer scope.
When outerFunction
is called, a new FEC is created, Inside outerFunction, we define innerFunction
, which has access to outerVariable
due to lexical scoping. After outerFunction
returns, the execution context of outerFunction
is removed from the call stack, but the innerFunction
retains access to outerVariable
because of the closure. So, when we later call closureExample()
, it can still log outerVariable even though the outerFunction has completed.
Real-World Applications of Closures
Let’s examine the following example:
function x(){
let a = 5
function y(){
console.log(a)
}
a = 50
return y;
}
let z = x();
console.log(z)
z();
What do you think the output of this code will be? Many of you might have guessed 5
, but is that really the correct output? Actually, no, and here’s why. The function y()
is referencing the variable a, not its initial value. When z()
is called, it logs the current value of a, which is 50
, due to the update made before returning the inner function. Let's explore another example:
function x(){
let a = 10;
function y(){
let b = 20;
function z(){
console.log(a,b);
}
z();
}
y();
}
x();
This
code demonstrates the power of closures. Even in the innermost function, z()
, it can still access variables from its parent scopes. If we inspect the browser and check the Sources tab, we can see that closures have formed on both x
and y
, which allows z()
to access a
and b
from its parent contexts.
Advantages of Using Closures
Closures offer several advantages in JavaScript, especially when writing more flexible, modular, and maintainable code. Below are some of the key advantages:
1. Callback Functions: Closures are very powerful when dealing with asynchronous programming, such as callbacks, event listeners, and promises. They allow the callback function to maintain access to variables from the outer function even after the outer function has completed.
function delayedLog(message, delay) {
setTimeout(function() {
console.log(message);
}, delay);
}
delayedLog('Hello after 2 seconds', 2000); // Logs after 2 seconds
2. Modularity and Maintainability: Closures encourage modularity by allowing developers to write smaller, reusable chunks of code. Since closures can preserve variables between function calls, they reduce the need for repetitive logic and improve maintainability.
3. Avoiding Global Variables: Closures help reduce the need for global variables, thus avoiding potential naming conflicts and keeping the global namespace clean. By using closures, you can store data in function scope rather than globally.
Conclusion
Closures are a powerful concept in JavaScript that extend the capabilities of functions by allowing them to remember and access variables from their outer scope, even after the function has executed. This feature plays a significant role in creating more modular, flexible, and efficient code, particularly when handling asynchronous tasks, callbacks, and event listeners. While closures might seem complex at first, mastering them will enable you to write more sophisticated and optimized JavaScript. As you continue to practice, you’ll discover how closures can help in writing cleaner, more maintainable applications. Keep experimenting, and soon closures will become a natural part of your JavaScript toolbox.
Top comments (0)