Which statement best describes a closure?
Closures come from lexical scope: the inner function remembers its outer environment and can use it later.
Closures · Exercise 1 of 4
Fifteen multiple-choice questions on JavaScript closures: the definition, environments per call, capturing variables, the loop problem, private state, the module pattern, memoization, stale closures, memory and this. Pick an option to check your answer instantly.
Which statement best describes a closure?
Closures come from lexical scope: the inner function remembers its outer environment and can use it later.
When does JavaScript create a closure?
Every function keeps a reference to the scope it was created in. Returning it is just the most visible way to use that environment later.
let n = 1; const f = () => n; n = 5; What does f() return?
Closures hold references to variables, not copies of values.
const c1 = makeCounter(); const c2 = makeCounter(); where makeCounter keeps let count = 0 inside. Do c1 and c2 share count?
Every invocation creates a new lexical environment with its own variables.
A function returns { inc: () => ++count, get: () => count } from one call. What do inc and get share?
Closures created during the same call close over the same environment.
Callbacks created in for (var i = 0; i < 3; i++) all print 3. What is the simplest fix?
let gives each iteration its own binding. Arrow functions change this, not scope; const would fail on i++.
In function createWallet() { let balance = 0; return { add: (n) => (balance += n) }; }, how can outside code change balance?
balance exists only in the factory's environment. The returned methods are the only door to it.
Which statement about closures and memory is true?
Once nothing refers to the closure (e.g. a listener is removed), its environment can be garbage-collected. Long-lived closures should avoid capturing large unused data.
What makes the module pattern const store = (function () { let items = []; return { add, list }; })(); work?
The IIFE runs once, creating a private scope; the public methods keep that scope alive.
A click handler closes over a large array. When can that array be garbage-collected?
Reachability decides: an attached listener keeps its closure, and therefore the array, alive.
Timed online tests with instant scores and explanations.