A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing. This happens because JavaScript uses lexical scoping.
Consider this example:
function createCounter() { let count = 0; return { increment: () => ++count, getCount: () => count, }; }
const counter = createCounter(); counter.increment(); counter.increment(); console.log(counter.getCount()); // 2
The count variable is encapsulated inside createCounter. It cannot be accessed directly from outside, but the returned methods form closures over it. This is the foundation of the module pattern and data privacy in JavaScript.
Closures are essential for callbacks, event handlers, and functional programming patterns like currying and partial application. They also power React hooks — every useState setter is essentially a closure over the state variable.
Understanding closures helps you write cleaner, more secure code and avoid common pitfalls like accidental shared state in loops.