Skip to the solution
MediumFrontend8 min read

What are closures in JavaScript?

546 views

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.

  • closures
  • scope
  • functions
  • lexical environment

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptvar vs let in a loop: one shared binding vs one per iteration (run directly)
JavaScriptPrivate state via a closure factory (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 84 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How would you use IntersectionObserver to lazy-load images only as they scroll into the viewport?

Continue