Function Declarations vs Expressions
What is the scope chain in JavaScript?
The scope chain in JavaScript is a series of nested contexts that JavaScript uses to resolve variable lookups. When code tries to access a variable, JavaScript first looks in the current scope (local scope). If the variable isn't found there, it looks up the chain to the parent scope, then that scope's parent, and so on until it reaches the global scope. This chain of nested scopes forms the scope chain. Each function in JavaScript creates its own scope, and functions defined inside other functions have access to their parent function's scope. This hierarchical arrangement allows inner functions to access variables from their outer functions (creating closures) but not vice versa. The scope chain is determined lexically (by the physical location of the code in the source), not by the call stack. Understanding the scope chain is essential for predicting how variable lookups will be resolved and for creating proper closures in JavaScript.