Block scope and variable shadowing in JS

Vijaya ShreeVijaya Shree
1 min read

To understand shadowing in JavaScript, we need to be clear with the scope first.

Refer the below link :

SCOPE

Shadowing is nothing but a variable replacing the value of another variable inside a block if declared with same name.

var a = 10 ;
            {
               var a = 100;
                console.log(a); // displays 10
             }
          console.log(a)// displays 10

The variable inside block shadows the variable in global space and the value gets replaced. Same applies with let and const as well.

Now, while shadowing a variable, it should not cross the boundary of the scope, i.e. we can shadow var variable by let variable but cannot do the opposite.It is called as illegal shadowing.

For example :

let a = 10;
                  {
                     var a = 100;
                    console.log(a);//  throws syntax error since a has already been declared with let in its local scope , since it won't be there in global scope it throws error 
                  }
0
Subscribe to my newsletter

Read articles from Vijaya Shree directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vijaya Shree
Vijaya Shree