Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Lexical Scoping

Lexical Scoping 12 min

javascript / Lexical Scoping

Explore each scene at your own pace.

01 · Lexical Scoping

Lexical Scoping

Lexical Scoping

Lexical scope resolves names according to where functions are written, rather than where they are called.

A function carries access to its definition’s surroundings, not its caller’s local names.

See the mechanism

Walk through the modelLexical ScopingAuthored snapshots of the example; use Run below to test the code.
StatereadCategory defined in outer scope
Its surrounding lexical environment is determined here.
1 of 3

Follow one example

javascript

readCategory was defined outside showArticle, where its lookup reaches the outer category. Calling it inside a function with another category does not relocate its definition. If readCategory were defined inside showArticle, it would instead see that enclosing local binding.

Predict, change and check

Predict: Does moving the call change the name lookup in the same way as moving the definition?

Test your explanation: Move only the definition inside showArticle and compare the output. Draw the containing scopes in each version.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Source nesting selects a scope relationship

Lexical scoping resolves a free identifier according to the scopes established by source nesting, not according to whichever function happened to call the function later. A caller's local variable with the same name does not dynamically become the callee's outer binding.

Shadowing creates a nearer binding; it does not rename or overwrite the outer binding just by existing. Use a small example with two functions that both declare title and then move the call site. Predict which declaration the function body can actually see before running the experiment.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.