Skip to content
UniCircle
GuideEngineeringB.Tech / B.E., BCA, MCA

JavaScript closures in 10 minutes

What a closure is, why a function remembers the variables around it, and three places closures show up in real code and in interviews.

By UniCircle team2 min readPublished 22 Oct 2026Undergraduate

A closure is a function together with the variables that were in scope where the function was created. The function keeps access to those variables even after the outer function has returned.

The smallest example

JavaScript
function makeCounter() {
  let count = 0;
  return function () { count += 1; return count; };
}
const next = makeCounter();
next(); next();
console.log(next());
const other = makeCounter();
console.log(other());
text
3
1

count is not global and not visible from outside, yet the returned function can still read and change it. Each call to makeCounter creates a fresh count, so other starts again from 1.

Where closures appear

1. Private state. Only the functions you return can touch the data.

JavaScript
function createWallet(start) {
  let balance = start;
  return {
    spend(amount) { if (amount > balance) return 'not enough'; balance -= amount; return balance; },
    get balance() { return balance; }
  };
}
const w = createWallet(500);
console.log(w.spend(120), w.spend(1000), w.balance);
text
380 not enough 380

2. Functions that make functions.

JavaScript
const multiplier = factor => n => n * factor;
const double = multiplier(2), gst = multiplier(1.18);
console.log(double(21), gst(100).toFixed(2));
text
42 118.00

3. Callbacks and timers. A callback passed to setTimeout or an event listener uses the variables around it when it finally runs, which is why the var-in-a-loop question gives surprising answers.

How to explain it in an interview

"A closure is when an inner function keeps a reference to variables from the scope where it was defined. That lets us create private state and specialised functions. The cost is that the variables stay in memory as long as the function is reachable." Then show the counter. Practise more in UniCircle interview prep: JavaScript and TypeScript.

#javascript#closures#functions#interview

Sources and further reading

Practise this as an interview question

Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.

Keep reading