Skip to solution
mediumFrontend

What are closures in JavaScript?

546 views
01

Understand the problem

Question presented to candidate: "What is a closure in JavaScript, and can you show me a case where getting them wrong causes a real, observable bug?"

What a strong answer should cover:

  • A closure is a function bundled together with a live reference to the variables of the scope it was defined in, not a snapshot of their values at the moment it was created.
  • That live reference survives even after the outer function has already returned and its call frame would otherwise be garbage collected.
  • Two separate calls to the same outer function produce two fully independent closures with separate private state; two closures created from the SAME call share the exact same variable binding.
  • The classic var-vs-let loop bug: closures created inside a var loop all share ONE binding and read whatever its final value ended up being, while let creates a fresh binding per iteration so each closure captures its own value.
  • Closures are the mechanism behind private state (the module pattern), memoization/caching, and function factories.

Clarifying questions expected:

  • "Do you want me to focus on closures specifically, or would it help to first cover how scope lookup works in general?" (lexical scoping is the broader mechanism closures are built on top of)

Code / implementation expected: Yes -- a short runnable snippet demonstrating the var-vs-let loop-capture difference with real observed output.

closuresscopefunctionslexical environment
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for JavaScript fundamentals interview questions. Difficulty: Medium

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. Every result below was actually run on Node.js v24.19.0 — the printed output is

Solution ready — 2 min read

Classified // press E to declassify

04

Run the code

JSvar vs let in a loop: one shared binding vs one per iteration (run directly)
JSPrivate state via a closure factory (run directly)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 84 of 165 decoded in the JavaScript track. One more won't hurt.

Back to track