🟑 MediumClosures & ScopeπŸ’» Output Question

Closure in object methods

πŸ’‘

Hint

Arrow functions capture the enclosing scope's variables directly. Object method arrows don't use this β€” they close over the lexical value.

What does this output?

function makeObj(value) {
  return {
    value,
    getValue() { return this.value; },
    getValueArrow: () => value,
  };
}

const obj = makeObj(42);
const fn = obj.getValue;

console.log(obj.getValue());
console.log(fn());
console.log(obj.getValueArrow());

Correct Output

42
undefined
42

Why this output?

Explanation: obj.getValue() β€” this=obj, returns 42. fn() β€” this is global/undefined, this.value=undefined. getValueArrow: arrow closes over makeObj's "value" param (42) at creation β€” ignores this entirely.

Key Insight: Arrow functions capture the enclosing scope's variables directly. Object method arrows don't use this β€” they close over the lexical value.

More Closures & Scope Output Questions

🟒 EasyClassic var in loop closureβ†’πŸŸ’ Easylet in loop closure (fix)β†’πŸŸ‘ MediumClosure counterβ†’πŸŸ‘ MediumIIFE closureβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz