Understanding JavaScript Closures: Unlocking Scope Secrets
Written on
Chapter 1: The Essence of Closures
JavaScript closures provide a unique way to manipulate scope. Typically, when a function completes its execution, any local variables it used are discarded. However, closures permit inner functions to retain access to variables from their parent function, even after the parent has executed. This behavior is akin to the inner functions capturing and preserving the local state of their parent.
To illustrate how closures function, consider this example:
function parent() {
const secret = "ssh, don't tell!";
return function() {
console.log(secret);
}
}
const inner = parent();
inner(); // Logs "ssh, don't tell!"
In this case, although the parent function has finished running, the inner function still retains access to the secret variable defined in the parent.
When a function is defined in JavaScript, it retains the context in which it was created, including all accessible variables and functions at that time. This characteristic of remembering its surrounding environment is what defines a closure. Therefore, each time the function is executed in the future, it can still utilize those variables and functions from its original context.
Closures are particularly beneficial when you require a function to hold private and persistent data that is shielded from external access. Prior to the introduction of class syntax in ES6, closures were often used to simulate private methods and variables in JavaScript.
For example, a closure can be employed to generate a counter that tracks the number of times it has been invoked:
function counterMaker() {
let count = 0;
return function counter() {
return count++;}
}
const myCounter = counterMaker();
myCounter(); // 0
myCounter(); // 1
myCounter(); // 2
In this scenario, the counter function maintains a closure over the count variable, incrementing it each time it is called. Importantly, external code cannot unintentionally alter countβit remains private!
Closures empower functions to maintain access to variables from their parent scope even after the parent has returned, providing persistent data and private state without the necessity of employing classes.
In Plain English π
Chapter 2: Exploring Closures Further
The first video titled "Learn Closures In 7 Minutes" provides a concise overview of closures in JavaScript, breaking down their essential aspects and practical applications.
In the second video, "How do closures work? (JavaScript Fundamentals, 2023)," the concept of closures is explored in-depth, covering their significance and functionality in JavaScript programming.