๐Ÿ”’ JavaScript

JavaScript Closures Explained With Real Examples

๐Ÿ“… Jun 12, 2026 โฑ 5 min read

The #1 JavaScript interview topic. One sentence: a closure is a function that remembers the variables from where it was created, even after that place has finished running.

The canonical example

function counter() {
  let count = 0;            // private variable
  return function () {
    return ++count;          // still sees count!
  };
}
const inc = counter();
inc(); // 1
inc(); // 2  โ€” count survives between calls

counter() finished executing, yet count lives on โ€” captured in the returned function's closure. Nothing outside can touch it: that is genuine privacy.

Where you already use closures

Interview follow-up

"What is the downside?" โ€” memory: closures keep captured variables alive, so giant objects captured accidentally cannot be garbage-collected.

Practice with the 100 JS interview questions.

โ† All Articles