A closure in JavaScript occurs when a function retains access to variables from its lexical (outer) scope, even after the outer function has finished executing. In short:
JavaScript uses lexical scoping, meaning a function can access variables defined where it was created.
function outer() {let count = 0;return function inner() {count++;return count;};}const increment = outer();increment(); // 1increment(); // 2
Even though outer() has completed, inner() still has access to count. That preserved variable is the closure.
Closures enable data encapsulation by keeping variables private and exposing only controlled APIs.
function createCounter() {let count = 0; // privatereturn {increment() {count++;},getValue() {return count;}};}const counter = createCounter();counter.increment();counter.getValue(); // 1counter.count; // undefined
Here, count cannot be accessed or modified directly, ensuring safer and cleaner code.
Closures are essential for: