CodeZettaInterview Hub

JavaScript · Closures · Fresh / Intern · Concept

What is a closure in JavaScript?

Short Interview Answer

A closure is a function bundled with its lexical environment, so it can access outer-scope variables even after the outer function has returned.

Detailed Explanation

When a function is created, it retains a reference to the lexical environment where it was defined. If it references outer variables, those bindings stay reachable as long as the function (or anything holding it) lives — that pairing is a closure. Closures enable data privacy (factory functions), partial application, callbacks that remember state, and module patterns. They are not a special syntax; they are a consequence of lexical scoping.

Example

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}
const c = makeCounter();
c(); // 1
c(); // 2

Interview Tip

Define it in one sentence, then give a tiny counter example.

Common Mistake

Saying closures only exist when you return a function — any nested function that uses outer variables forms a closure.

Did you know this answer?