What Are Closures in JavaScript?
Closures are a fundamental concept in JavaScript that can seem tricky but are incredibly powerful. Here's a quick guide to understanding them.
What is a Closure?
A closure is created when a function "remembers" the variables from its lexical scope, even after that scope has exited.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const myClosure = outerFunction("Hello");
myClosure("World");
// Output: Outer: Hello, Inner: World
Here, innerFunction
has access to outerVariable
from outerFunction
's scope, even after outerFunction
has finished executing.
Why Are Closures Useful?
Data Privacy: Create private variables.
function counter() {
let count = 0;
return function () {
count++;
return count;
};
}
const myCounter = counter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
Partial Application: Pre-fill function arguments.
function multiplyBy(multiplier) {
return function (number) {
return number * multiplier;
};
}
const double = multiplyBy(2);
console.log(double(5)); // 10
Conclusion
Closures let functions remember their environment. They’re great for private variables, partial application, and many other advanced patterns in JavaScript.
Top comments (0)