Hoisting and Execution Context
What is the scope chain in JavaScript?
The scope chain in JavaScript is a hierarchical chain of nested scopes that determines variable access. When JavaScript tries to resolve a variable reference, it first looks in the current scope (local execution context). If it doesn't find the variable there, it looks in the next outer scope, and continues up the chain until it either finds the variable or reaches the global scope. If the variable isn't found in the global scope, a ReferenceError is thrown. The scope chain is created during the creation phase of an execution context and is based on lexical scoping - where functions are defined in the code, not where they're called from. Each execution context has a reference to its outer environment, forming links in the chain. For example: ```javascript const global = 'global'; function outer() { const outerVar = 'outer'; function inner() { const innerVar = 'inner'; console.log(innerVar, outerVar, global); // Can access all three } inner(); } ``` When `inner()` executes, its scope chain includes its own scope, `outer()`'s scope, and the global scope, allowing it to access variables from all three scopes. This mechanism enables closures and is fundamental to understanding variable access in JavaScript.