🔒 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