Question 04 / 14
Can global code read a variable declared inside a function?
Topic: Lexical scope
A function-local var binding is not visible from the outer global environment.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
The function has already returned. Does its local b become global afterward?
var a = 10;
(function () {
var b = 20;
})();
console.log(a);
console.log(b);Reveal the answer and explanation
Expected output
10
Uncaught ReferenceError: b is not definedWhy this happens
a is a global var binding, so the first log prints 10.
b belongs to the environment created for the immediately invoked function. Returning from that call does not copy b into the global environment.
The later lookup for b from global code fails and throws ReferenceError.
What this question tests
- function scope
- environment lifetime
- failed outer lookup
Runtime assumptions
Run as non-module script code. The visibility conclusion is unchanged in modules.