Functions, Closures & Lexical this Binding (Arrow Functions)
1Concept
A Closure is a function bundled with references to its lexical environment. Arrow functions (() => {}) do NOT bind their own this, arguments, or super; they inherit this from enclosing lexical scope.
2Architecture Diagram
function outer() {
let count = 0;
return function inner() { count++; return count; }; // Retains reference to 'count'!
}3Code Example
Stage 0 Language Foundations
function createCounter(initial) {
let count = initial; // Private variable encapsulated by closure
return {
increment: () => ++count,
decrement: () => --count,
get: () => count
};
}
const counter = createCounter(10);
console.log(counter.increment());
console.log(counter.increment());
console.log(counter.get());4Expected Output
11 12 12
5Key Takeaways
- ✓Closures enable data privacy and module factory patterns.
- ✓Arrow functions inherit 'this' lexically from surrounding code.
- ✓Avoid storing large unused variables in closures to prevent memory leaks.