1. What is Scope?
Scope means the area of a program where a variable can be accessed.
let name = "Abishek";
console.log(name);
Here, name can be accessed because it is available in that scope.
2. What is Scope Chain?
Scope Chain is the process JavaScript uses to find a variable.
When JavaScript needs a variable, it first searches in the current scope. If it is not found, it searches in the outer scope. It continues searching until it reaches the global scope.
Simple Flow
Current Scope
↓
Outer Scope
↓
Global Scope
3. Example of Scope Chain
let a = 10;
function outer() {
let b = 20;
function inner() {
let c = 30;
console.log(a);
console.log(b);
console.log(c);
}
inner();
}
outer();
There are three scopes:
Global Scope
↓
outer() Scope
↓
inner() Scope
Finding c
JavaScript searches:
inner scope → c found ✅
So:
30
Finding b
JavaScript searches:
inner scope → b not found ❌
↓
outer scope → b found ✅
So:
20
Finding a
JavaScript searches:
inner scope → a not found ❌
↓
outer scope → a not found ❌
↓
global scope → a found ✅
So:
10
4. What if the Variable is Not Found?
If JavaScript searches the entire scope chain and cannot find the variable, it gives a ReferenceError.
function test() {
console.log(x);
}
test();
JavaScript searches:
test scope → x ❌
↓
global scope → x ❌
Since x is not found:
ReferenceError: x is not defined
5. Inner Scope Can Access Outer Scope
An inner function can access variables from its outer scope.
function outer() {
let a = 10;
function inner() {
console.log(a);
}
inner();
}
outer();
Output:
10
Why?
Because JavaScript searches outward:
inner → outer → global
6. Outer Scope Cannot Access Inner Scope
An outer function cannot access variables declared inside an inner function.
function outer() {
function inner() {
let b = 20;
}
console.log(b); // Error
}
b belongs only to the inner scope.
The scope chain does not search inward.
outer → inner ❌
It only searches outward:
inner → outer → global
7. Important Rule
Scope Chain always searches:
Inside → Outside
or
Current Scope → Parent Scope → Global Scope
It does not search:
Outside → Inside
The inner scope can access outer variables, but the outer scope cannot access inner variables.
Top comments (0)