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 defined

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

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