Closures & Lexical Scoping
02 // Simple Explanation (Mental Model)
A closure is a function bundled together with references to its surrounding state (lexical environment). In simple terms, it gives an inner function access to an outer function's scope even after the outer function has returned.
03 // Technical Deep Dive & Internals
When a function is declared in JavaScript, an internal [[Environment]] slot captures the current Lexical Environment record. When the outer function finishes executing, its execution context is popped off the call stack, but its Lexical Environment Record remains in heap memory as long as the inner function retains a reference to it.
function createCounter(initialValue = 0) {
let count = initialValue;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.getValue()); // 1105 // Real-World Production Architecture
Encapsulating private state, creating factory functions, currying, and memoization caches without exposing variables to the global scope.
06 // Common Pitfalls & Mistakes to Avoid
Creating functions inside loops without let (old var issue), and memory leaks when unreferenced closures hold large objects in outer scope.
09 // Quick Revision Notes (Pre-Interview Spec Sheet)
A closure retains access to the outer function's scope even after the outer function has finished executing.