The scope chain helps JavaScript find variables by looking in the right places step-by-step.
Scope chain in Javascript
function outer() { let outerVar = 'hello'; function inner() { console.log(outerVar); } inner(); }
Variables are looked up starting from the current function, then moving outward.
If a variable is not found in the current scope, JavaScript checks the next outer scope.
sayHello uses the variable name from the outer function.function greet() { let name = 'Alice'; function sayHello() { console.log('Hello ' + name); } sayHello(); } greet();
check accesses a variable from the global scope.let globalVar = 'I am global'; function check() { console.log(globalVar); } check();
x, so it prints 2, then the outer prints 1.function outer() { let x = 1; function inner() { let x = 2; console.log(x); } inner(); console.log(x); } outer();
This program shows how the scope chain works with two variables named message in different scopes.
function outer() { let message = 'Hi from outer'; function inner() { let message = 'Hi from inner'; console.log(message); // inner message } inner(); console.log(message); // outer message } outer();
Each function creates a new scope for its variables.
If a variable is not found in the current scope, JavaScript looks outward until it finds it or reaches the global scope.
Variables declared with let and const are block-scoped, meaning they only exist inside the block they are declared in.
The scope chain is how JavaScript finds variables by checking current and outer scopes.
Inner functions can access variables from outer functions.
Variables with the same name in inner scopes hide outer ones.