🔗 Scope Chain — How Variables are Resolved in JavaScript

When you write JavaScript, you often use variables declared in different scopes. Have you ever wondered how JavaScript knows which variable to use when there are many with the same name? The answer lies in the scope chain.
🌟 What is a Scope?
A scope is a context in which variables are declared and accessed. JavaScript has two main types:
Global scope: Variables accessible everywhere.
Local (function or block) scope: Variables accessible only inside a function or block.
🔗 What is Scope Chain?
When you try to access a variable, JavaScript starts looking in the current scope. If it doesn’t find it, it moves to the outer scope, and continues until it reaches the global scope. This chain of scopes is called the scope chain.
🧩 Example
let a = "global";
function outer() {
let b = "outer";
function inner() {
let c = "inner";
console.log(a); // global
console.log(b); // outer
console.log(c); // inner
}
inner();
}
outer();
What happens here?
inner
function looks fora
,b
, andc
.c
is found ininner
.b
is found inouter
.a
is found in global scope.
💡 Important Points
✅ Inner functions have access to outer function variables, but not the other way around.
✅ Each function creates a new scope.
✅ Global variables are always at the end of the scope chain.
⚠️ Shadowing
When a variable in an inner scope has the same name as one in an outer scope, it shadows the outer one.
let value = "global";
function test() {
let value = "local";
console.log(value); // local
}
test();
console.log(value); // global
🧭 Why is it important?
Understanding the scope chain helps you:
Avoid unexpected bugs
Write predictable code
Understand closures and advanced JS patterns
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
