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:
- Buy me a coffee at buymeacoffee.com/safdarali
- Subscribe to my YouTube channel — it's free; 70+ React & Next.js tutorials
Related reading
More guides on safdarali.in — same author, production-focused.
- Guide
How to Build a Frontend Developer Portfolio That Stands Out
Frontend developer portfolio guide for India — sections, React/Next.js examples, SEO, performance, personal branding, FAQ, and checklist to build and rank.
May 2026Read article →
- Guide
React Server Components vs Client Components — When to Use Which
Practical RSC vs client guide for Next.js App Router — when to use each, real code, bundle before/after, and performance impact.
May 2026Read article →