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
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());3
1count 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.
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);380 not enough 3802. Functions that make functions.
const multiplier = factor => n => n * factor;
const double = multiplier(2), gst = multiplier(1.18);
console.log(double(21), gst(100).toFixed(2));42 118.003. 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.
