JavaScript Closures Explained with Real Examples

Closures are one of JavaScript’s most fundamental concepts and one of the most commonly misunderstood — every function in JavaScript forms a closure over its surrounding scope, whether you realize it or not.

function makeCounter() {
    let count = 0; // private to this specific counter instance
    return {
        increment: () => ++count,
        reset: () => { count = 0; },
        getValue: () => count,
    };
}

const counterA = makeCounter();
const counterB = makeCounter();
counterA.increment();
counterA.increment();
console.log(counterA.getValue()); // 2
console.log(counterB.getValue()); // 0 - completely separate closure, own private count

A closure is simply a function that “remembers” the variables from where it was created, even after that outer function has finished running. This is exactly how JavaScript achieves private state without classes — count is genuinely inaccessible from outside except through the returned methods.