Lesson 2 of 80
A function remembers the variables from where it was born — even after that place is gone. The idea behind debounce, counters, and React's useState.
15 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
In the debounce example, what keeps `timer` alive after debounce() has already returned?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
A closure is a function that remembers the variables around it from where it was created, even after the outer function has finished running.
From the scope lesson: inner code can reach outward. A closure is what happens when you keep that inner function around after the outer one returns — it drags its outer variables along with it.
A debounce says "wait until the user stops typing for 300ms, then run." Here's the core, and the closure is doing all the work:
function debounce(fn, delay) {
let timer; // lives in the outer room
return function (...args) {
clearTimeout(timer); // the returned fn still sees `timer`
timer = setTimeout(() => fn(...args), delay);
};
}
debounce returns and is gone — but the returned function still holds a live reference to timer. That surviving reference is the closure. Without it, every call would start with a fresh timer and nothing would ever get cancelled.
makeCounter() runs. It creates a variable count, and a function increment that uses it.
var in a for loop with an async callback captures one shared variable, so every callback sees the final value. let gives each iteration its own binding and fixes it.debounce twice gives two independent timers; they don't interfere.useState in React is a closure over the component's state cell. Event handlers you pass around are closures over their surrounding variables. The module pattern hides private data in a closure. Learn this one idea, and four other things click.