Closure
Written on by .
The Secret Garden
Imagine a secret garden that's surrounded by a tall wall. Inside the garden, there are various plants and a gardener who takes care of them. The gardener has a unique ability: even when they step out of the garden, they can still magically tend to the plants within the walls. This garden is like the function's lexical scope, the plants are the variables within that scope, and the gardener is the closure, able to access and modify those variables even from outside the garden's walls.
Whispers of Scope
Garden walls confine,
Leaves whisper, secrets kept close,
Closure's silent bind.
The Secret Gardener's Scope
function secretGarden() {
let secretPlants = "Bonsai"; // A plant in the secret garden
function gardener() {
// The gardener can access secretPlants even outside the garden
console.log(`Tending to the ${secretPlants} with care.`);
}
return gardener;
}
let gardenAccess = secretGarden(); // The gardener steps outside
gardenAccess(); // Still tending to the Bonsai: "Tending to the Bonsai with care."
Closure
Can Linger Over Scope Unseen, Reaching Everywhere
Concept Checking Questions
1. What is a closure in JavaScript?
- A closure is a function that remembers the variables from the place where it was defined, regardless of where it is executed.
2. How does a closure differ from a global or local variable?
- A closure can access variables from its outer function scope even after that function has executed, which is not the case for typical global or local variables that have their access limited to their defined scope.
3. Can you give an example of a practical use of closures?
- Closures are useful for creating private variables or functions that can't be accessed from the global scope, effectively encapsulating them for security or design purposes.