Scope Chain Lookup
What you'll learn: How JavaScript searches through nested scopes to find variables, moving outward until it succeeds or reaches global scope.
The Search Path
When JavaScript encounters a variable, it doesn't magically know where that variable was declared. Instead, it follows a systematic search process called scope chain lookup.
The engine starts in the current scope where the variable is referenced. If it doesn't find the variable there, it moves outward to the next enclosing scope. This continues, level by level, until JavaScript either finds the variable or reaches the global scope and gives up.
The Lookup Process
Think of scope chain lookup like searching for your keys in nested boxes. You check the smallest box first (current scope). Not there? Check the box that contains it (parent scope). Still missing? Keep opening larger boxes until you find your keys or run out of boxes to check.
The search is always outward, never inward. A parent scope cannot see variables declared in its children.
Example Without Code
Imagine a function inside another function inside the global scope. If the innermost function uses a variable, JavaScript:
- Checks the inner function's scope first
- If not found, checks the middle function's scope
- If still not found, checks the global scope
- If nowhere to be found, throws a ReferenceError
The chain stops at the first match. If the inner function has a variable with the same name as one in global scope, JavaScript uses the inner one and never looks further.
Key Takeaway: JavaScript resolves variables by searching outward through the scope chain, stopping at the first match or throwing an error if the variable is never found.