What is a "stale closure"?
Typical case: a timer created once reads a snapshot (or an old state variable) and never sees later updates.
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.
What is a "stale closure"?
Typical case: a timer created once reads a snapshot (or an old state variable) and never sees later updates.
Which functions effectively take this from the surrounding scope, the way closures take variables?
Regular functions get this from how they are called. Arrow functions have no own this and look it up lexically.
Why does memoize(fn) need a closure?
The cache is created once in memoize's scope and remembered by the returned function across calls.
Why does for (var i = 0; i < 3; i++) fns.push(((n) => () => n)(i)); produce functions returning 0, 1 and 2?
The inner arrow closes over n, a fresh variable per call – the pre-ES6 solution to the loop problem.
const next = (() => { let n = 0; return () => n++; })(); What does the third call next() return?
Postfix n++ returns the old value: the calls return 0, 1, 2.
Timed online tests with instant scores and explanations.