Scope chain and lexical scope in JavaScript
global scope, local scope, block scope, scope chain, lexical scope, variable shadowing, scope lookup order, nested functions
How JavaScript Finds Variables
When JavaScript encounters a variable name, it searches for a declaration starting in the current scope and moving outward until it finds one or hits the global scope. This is the scope chain.
Lexical Scope
Scope is determined at the time code is written, not when it runs. A function can always access variables from the environment where it was defined.
const city = "London"; // global
function outer() {
const country = "UK";
function inner() {
const street = "Baker St";
// can access: street, country, city
console.log(street, country, city);
}
inner();
// cannot access: street (block-scoped inside inner)
}
Variable Shadowing
A variable in an inner scope can have the same name as one in an outer scope. The inner one shadows โ hides โ the outer one within its scope.
const x = 10;
function demo() {
const x = 20; // shadows outer x
console.log(x); // 20
}
console.log(x); // 10 โ outer unchanged
Why This Matters
Misunderstanding scope is the root of bugs where variables seem to have wrong values. Trace the scope chain from the code location outward to understand exactly what any identifier resolves to.
