What is a closure, and where does it cause UI bugs?
Understand the idea, explain it in your own words and use the rubric to find your next learning gap.
The idea behind the question
A function retains access to its lexical environment. In UI code, the important question is which value a callback observes when it eventually runs.
An event handler schedules a timeout and the user changes state before that timeout fires.
A practical way to learn it
Write a closure-based counter in JavaScript, then predict a timeout's output before running it.
Open JavaScript playgroundThe related tool opens separately; your interview answer stays here. Written practice is self-guided, without automatic code grading.
Build an explanation you understand
- State what the concept does in plain language.
- Apply it to the example and make your assumptions explicit.
- Explain a trade-off, failure case and how you would test it.
- Distinguish your actual experience from a proposed approach.
How would you explain it?
Single-question timers reset on refresh. Full mock sessions can resume from this browser.
Strengthen your explanation
Compare reasoning, not identical wording. Reference answers describe a possible approach; replace hypothetical statements with truthful details from your own work.
One way to answer
I would explain a closure with a small function that returns another function using an outer variable. In React, an event handler belongs to a render and can observe that render's state snapshot later. I would identify whether the task needs the captured value, a functional state update or an explicitly maintained current reference. I would not call every delayed callback a bug: sometimes capturing the value at the moment of the click is intentional. I would reproduce the timing behavior before choosing a fix.
What a strong explanation should cover
Tick only the points your own answer addresses. This is self-assessment, not AI scoring.
0 / 3 points self-reportedWatch out for
- Saying a closure always contains the latest React state.
Now go one level deeper
- How does a functional updater help an increment?
- When would a ref hide a design mistake?
Further reading
Further-reading links support learning; the reference is Sukoaa-authored, not an official employer answer key.