Skip to main content

Nov 2026 · Guide · ~8 min read

JavaScript Closures — The Explanation I Use in Interviews

By Safdar Ali — frontend engineer, Bengaluru

I'm Safdar Ali. A closure is a function plus the variables it can see from the scope where it was created. The function can run later. The variables are still the ones it captured. That is why a callback still knows the id from the render that created it.

The old var loop bug was one function per iteration that all saw the same binding. let gives each iteration its own binding, so the callback sees the value from that turn. If you can explain that without reading it off a card, you understand closures.

In React, a stale closure is an effect or a timer that captured state from an old render. The timeout fires and sets or reads the old count. The fix is to include the value in the effect dependencies, or to use a ref when you truly want the latest value inside a long-lived subscription.

I do not tell people to empty the dependency array and disable the lint rule. That freezes the closure on purpose and hides the bug until production. The lint is describing this article.

Closures are also why hooks work. useState does not put the variable on this. The component function closes over the state for that render. Next render, new closure, new values.

If this helped you

I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:

More guides on safdarali.in — same author, production-focused.

"Talk is cheap. Show me the code."