Javascript - The Scope Chain
Code Life
By Pierre Marsaa
The Scope Chain: Searching Outward
When you have scopes nested inside each other—like an if block inside a function, which is inside the global file—how does JavaScript find a variable?
It starts in the innermost scope and searches outward step by step until it finds the variable:
↗️
Loading editor...
↶
↷
When console.log runs inside the if block:
1.
It finds spot right inside the if block.
2.
It doesn't find area in the if block, so it steps out into explore() and finds area there.
3.
It doesn't find world in explore(), so it steps out to the global scope and finds world.
This step-by-step outward lookup is called the scope chain.
Verify