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

10

Why 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.

Specification references

JavaScript Code EditorDirectly edit or paste custom code
Step 0 of 0
StepSpaceRun
Press → (Step) or Space (Run)
Phase 1: Compilation(Hoisting & Memory Setup)
Phase 2: Execution(Line-by-line Evaluation)
Execution Step Breakdown

Press "→" / click "▶" to step line-by-line, or press "Space" / click "▶ Run" for auto-play.

Scope Chain
Lexical Environment Chain: Inner Scope → Outer [[Scope]] → Global (GO)
No active scope chain
CALL STACKStack of Execution Contexts (LIFO)
LIFO Stack Frames
Global Execution Context (GEC)
▶ Active Frame
HEAP & MEMORY SPACEAllocated Objects (GO, AO, FunctionObjects, ER)
ECMAScript Heap Area
No objects in memory
Console Output
console.log(...) Stream
No output generated yet