What is scope and the scope chain in JavaScript?
Answer
Scope determines where variables are accessible. JavaScript has three types: Global scope — variables declared outside any function are accessible everywhere. Function scope — variables declared with var inside a function are accessible only within that function and nested functions. Block scope — let and const are accessible only within the {} block they are declared in (if statements, loops, etc.). The scope chain is how JavaScript resolves variable names. When a variable is accessed, JavaScript first looks in the current scope, then moves up through enclosing scopes (parent function, grandparent function, global) until found or a ReferenceError is thrown. Closures capture the scope chain — inner functions can access outer function variables because they maintain a reference to the outer lexical environment. The scope chain is determined lexically at write-time (where you write the code), not at call-time — this is lexical scoping (or static scoping).
Previous
What is error handling in JavaScript?
Next
What is the difference between synchronous and asynchronous error handling?