π Understanding Scope in JavaScript

When we write JavaScript, one of the most important (and often confusing) topics is scope. Knowing how scope works helps you avoid bugs, write cleaner code, and understand how JavaScript engines execute your programs.
In this article, weβll break down scope step by step, covering:
Global scope
Function scope
Block scope
How different declarations (
var
,let
,const
) behave
π Global Scope
Variables declared outside of any function or block are in the global scope. They can be accessed anywhere in your code.
var globalVar = "I am global";
function showGlobal() {
console.log(globalVar);
}
showGlobal(); // "I am global"
console.log(globalVar); // "I am global"
ποΈ Function Scope
Functions create their own scope. Variables declared with var
inside a function are local to that function.
function example() {
var localVar = "I am local";
console.log(localVar);
}
example(); // "I am local"
console.log(localVar); // β ReferenceError
let
and const
in function scope
When declared inside a function, let
and const
also create local function scope variables. These variables cannot be accessed outside the function.
function test() {
let a = 10;
const b = 20;
console.log(a); // 10
console.log(b); // 20
}
test();
console.log(a); // β ReferenceError
console.log(b); // β ReferenceError
π¦ Block Scope (let
, const
, and var
)
Unlike var
, let
and const
are block-scoped, meaning they exist only within the block ({}
) where theyβre declared.
{
let blockLet = "Block scoped";
const blockConst = "Also block scoped";
}
console.log(blockLet); // β ReferenceError
console.log(blockConst); // β ReferenceError
var
inside a block
Variables declared with var
inside a block do not have block scope. Instead, they get hoisted to the enclosing function scope (or global scope if not inside a function).
{
var blockVar = "Not block scoped";
}
console.log(blockVar); // β
"Not block scoped"
π Shadowing and Memory Allocation
A variable declared in an inner scope can shadow a variable from an outer scope. When shadowing occurs, a new memory space is allocated for the inner variable, and the outer variable remains untouched.
let value = "Outer";
function demo() {
let value = "Inner"; // Shadows outer 'value'
console.log(value); // "Inner"
}
demo();
console.log(value); // "Outer"
When demo
runs, a new value
is created in its local scope memory. The outer value
in the global scope stays the same.
π Final Thoughts
Understanding scope in JavaScript is essential for avoiding subtle bugs and writing predictable, clean code. By mastering how var
, let
, const
, and functions interact with scope, you'll become much more confident in your JavaScript journey.
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
