Closures — JS Technical Interview Questions & Answers

A function that remembers variables from its outer scope.

Closures

  • Closures (js) is a JS topic. In plain words you use it for a click counter factory in a widget. Don’t start with a slogan — start with that picture.
  • Smallest example: inner function keeps outer count. Type it, run it, and say what you see. If you can do that from memory, you know Closures (js).
  • From the example next to this theory: A function that remembers variables from its outer scope.
  • Trap: var in a for-loop with listeners. Fix that before you talk about advanced JS.
  • Viva: what is Closures (js)? Then show inner function keeps outer count. Then name the trap.

Technical Interview Tip: What is Closures (js)? Show this: inner function keeps outer count. Trap: var in a for-loop with listeners.

Code Examples for Closures

Closures — working example

function makeCounter() {
  let n = 0;
  return function () {
    n += 1;
    return n;
  };
}
const next = makeCounter();
console.log(next(), next(), next()); // 1 2 3

function makeAdder(x) {
  return (y) => x + y;
}
console.log(makeAdder(5)(3));

Closures — a closure remembers variables from its outer scope after that scope finished.

How to Explain Closures to an Interviewer

What is Closures (js)?

Used for a click counter factory a widget Not just the heading

Give one small example of Closures (js).

inner function keeps outer count A function that remembers variables from its outer scope

What mistake do beginners make with Closures (js)?

var in a for-loop with listeners Show the fix

Where do you use Closures (js)?

a widget a click counter factory