Closures & ScopeBeginner
1Question 1 of 16
javascriptWhat is a closure in JavaScript and how does it retain access to outer variables?
Explanation & Concept
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
In JavaScript, closures are created every time a function is created, at function creation time. This allows an inner function to access variables from an outer enclosing function's scope even after the outer function has executed and returned from the call stack.
Closures are widely used for data privacy, state encapsulation, factory functions, and event-driven callbacks.
Code Example
javascript
function createCounter(initialValue = 0) {
let count = initialValue; // Private state encapsulated by closure
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.increment()); // 12
console.log(counter.decrement()); // 11
console.log(counter.count); // undefined (Encapsulated!)How It Works & Key Takeaways
Even though `createCounter` finished running, its lexical environment remains in memory because `increment`, `decrement`, and `getCount` maintain references to `count`. Direct modification of `count` from outside is impossible.