HardClosures & Scope💻 Output Question

Shared closure state across methods

💡

Hint

All methods from a factory share one closure scope — one private variable, multiple public operations.

What does this output?

function createObj() {
  let val = 0;
  return {
    inc()   { val++; },
    dec()   { val--; },
    reset() { val = 0; },
    get()   { return val; },
  };
}
const obj = createObj();
obj.inc(); obj.inc(); obj.inc(); obj.dec();
console.log(obj.get());
obj.reset();
console.log(obj.get());

Correct Output

2
0

Why this output?

Explanation: All four methods close over the same val variable. They share and mutate the same binding.

Key Insight: All methods from a factory share one closure scope — one private variable, multiple public operations.

More Closures & Scope Output Questions

EasyClassic var in loop with setTimeoutEasylet in loop — each iteration gets own bindingMediumIIFE captures loop variableMediumClosure mutation persists across calls

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz