Closures & scope · Output question
JavaScript closures and a changing outer variable
A function reads an outer variable whose value changes before the call. Predict whether the function sees the old or current value.
let label = "draft";
const read = () => label;
label = "ready";
console.log(read());What gets logged?
Choose an output before opening the walkthrough, or check your answer in practice mode.
Reveal the answer and execution trace
readyThe function closes over the label binding. It reads the binding when called.
- Line 2. read remembers where label lives in the surrounding scope.
- Line 3. The label binding is updated to "ready".
- Line 4. Calling read looks up the current value.
Reference: Lexical environments on MDN.