Variable Shadowing in JavaScript (original) (raw)

Last Updated : 01 Feb, 2025

Variable Shadowing in JavaScript occurs when the inner variable hides or overrides the outer variable within the local scope. In this situation, the outer variable cannot be accessed within the inner scope, only the inner variable is used in that scope.

let n = 5; // Outer variable function a() { let n = 10; // Inner variable that shadows the outer one console.log(n); // 10 (inner n is used here) } a(); console.log(n); // 5 (outer n is still used here)

`

**In this example

How Variable Shadowing Works in JavaScript?

1. Shadowing with var

When we declare the variable with var, it only exists within the function in which it is declared even if it is inside an if or for loop. If we have a variable with the same name outside the function, the variable inside the function will hide the outer one.

JavaScript `

var n = 10; // Outside the function

function t() { var n = 20; // Inside the function, 'n' is different console.log(n); // Prints 20 }

t(); console.log(n); // Prints 10 (the one outside the function)

`

2. Shadowing with let and const

When we declare the variable with the let or const, the variable only exists inside the block (like an if statement or a loop). If we use the same name for a variable inside the block, it will hide the one outside the block. This is different from var, which is only limited to the function.

JavaScript `

let n = 10;

if (true) { let n = 20; // Shadows the outer 'a' console.log(n); // 20 }

console.log(n); // 10

`

Due to the block scoping let the a inside the if block is different from the a in the outer scope.

Why Does Variable Shadowing Happen?

Variable Shadowing in JavaScript mainly happens when we declare the variable inside the local scope with the same name in the outer scope. Below are the mentioned reasons why variable shadowing happens

How to Avoid Issues with Variable Shadowing?