Imagine This...
You’re working on a project, and you need a function to "remember" the values of variables—even after the function has finished running. Closures are like a magical backpack that lets you carry knowledge from a previous lesson wherever you go in your code. It’s one of the most powerful yet misunderstood concepts in JavaScript. But don’t worry—by the end of this guide, closures will go from head-scratching to “aha!”
What’s a Closure? Simplified Definition and Analogy
A closure is when a function "remembers" its surrounding state (the variables in its scope) even after the outer function has finished executing. Let’s break this down with a relatable analogy:
Real-Life Analogy: The Backpack of Knowledge
Imagine you’re a student. You have a backpack with your notes, pens, and books. You leave the classroom (your outer function), but you still have access to everything in your backpack (your closure). Whenever you need to solve a problem later, you can pull out the knowledge you saved in your backpack.
Simplified Definition
In JavaScript, closures happen when:
- A function is defined inside another function.
- The inner function "remembers" the variables of the outer function.
How Do Closures Work? Examples in Action
Let’s see closures in action with code examples.
Example 1: A Basic Closure
function outerFunction() {
const outerVariable = 'Hello, Closure!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const myClosure = outerFunction();
myClosure(); // Output: "Hello, Closure!"
What’s Happening Here?
innerFunctionis returned fromouterFunction.- Even though
outerFunctionhas finished executing,innerFunctionstill remembersouterVariable.
Example 2: Closure for a Counter
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
What’s Happening Here?
- The returned function "remembers" the
countvariable, even thoughcreateCounterhas finished running. - Each time you call
counter, it updates and remembers the latest value ofcount.
Example 3: Closures in Loops (Common Pitfall)
Closures often trip up developers when used inside loops.
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), i * 1000);
}
// Output: 1, 2, 3 (each after 1 second)
Why Does This Work?
- The
letkeyword creates a block scope, so each iteration has its owni. - If you used
varinstead oflet, all outputs would be4becausevardoesn’t create block scope.
📄 Documentation:
Connect on LinkedIn
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR