Skip to main content

Command Palette

Search for a command to run...

Shadowing in JavaScript (with var, let, const Examples)

Published
2 min read
S

Hi, I am a web developer, always curious and exploring new tech

Shadowing in JavaScript is an important concept because it helps us understand why variables can behave differently in certain situations.
By understanding shadowing, we can write cleaner, modular code and avoid unexpected bugs.

Variable Shadowing with let

Shadowing occurs when a variable declared in an inner scope has the same name as a variable in the outer scope.

function test() {
  let a = "Hello";

  if (true) {
    let a = "Hi"; // shadows outer 'a'
    console.log(a); // Hi
  }

  console.log(a); // Hello
}

test();

Explanation

  • The inner a shadows the outer a

  • Both variables exist in different scopes

  • This is valid shadowing


Illegal Shadowing in JavaScript

Illegal shadowing happens when a variable declared with var tries to shadow a let or const variable from an outer scope.

Rules to remember

  • let can be shadowed by let

  • var can be shadowed by let

  • let cannot be shadowed by var


function func() {
  var a = "Hello";
  let b = "Namaste";

  if (true) {
    let a = "Hi";   //  Legal shadowing
    var b = "Bye";  //  Illegal shadowing

    console.log(a);
    console.log(b);
  }
}

func();

Why is this illegal?

  • var b is function scoped

  • It tries to redeclare b which is already declared with let in the same function scope

  • JavaScript throws a SyntaxError