Chapter 1JavaScript · Theory

Lexical Scope & Scope Chain

A variable's scope is set by where it is written in the code, not by where the code is eventually called from.

JavaScript uses lexical scoping (also called static scoping): when you write a variable inside a function or block, that location in the source code determines where the variable is visible. Functions create their own scope. Blocks (if/for/while) create scope for let and const.

When JavaScript looks up a variable, it starts in the current function's scope, then moves outward to the surrounding scope, then outward again — all the way to the global scope if needed. This chain of scopes is called the scope chain. It is built when the code is written, not when it runs.

The scope chain explains two things that confuse beginners: inner functions can read variables from outer functions, but outer functions cannot reach into inner ones. It also explains why closures work — when an inner function is kept alive after its outer function returns, it still holds a reference to the outer scope through the chain.