Question 03 / 14
Does a function read variables from its caller, or from where it was defined?
Topic: Lexical scope
JavaScript uses lexical (static) scoping, so a function's scope chain is fixed by where it is written, not by who calls it.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
Predict the output. When foo runs inside bar, does it read the outer x or the x local to bar?
var x = 10;
function foo() {
console.log(x);
}
function bar() {
var x = 20;
foo();
}
bar();Reveal the answer and explanation
Expected output
10Why this happens
foo and bar are both declared in the global scope, so foo's outer environment reference always points to the global environment, no matter which function calls foo.
Calling bar() creates its own local x with the value 20, but that binding lives only inside bar's environment — it is never part of foo's scope chain.
Calling foo() from inside bar() still resolves x through foo's own scope chain: no local x, then the global x, which holds 10. The call site never changes that chain, so the output is 10.
What this question tests
- lexical scope
- scope chain is fixed at definition, not at call time
- no dynamic scoping in JavaScript
Runtime assumptions
This is standard lexical scoping behavior in any JavaScript environment; JavaScript never uses dynamic scoping.