Javascript: Variable Shadowing

let and const were introduced in the ES6 version of Javascript. Which enables the variable shadowing.

Let’s understand more about variable shadowing using an example:

let and const were introduced in the ES6 version of Javascript. Which enables the variable shadowing.

In the above example the variable a is shadowed inside the if block. The value of variable a is temporarily changed inside the if block and that change is only valid inside that block.

Outside the if block the value of variable a is the same old variable that is given in line 5.

Variable Shadowing

  • var can be shadowed by let (refer 1 in image below)
  • let cannot be shadowed by var , it is called illegal shadowing [throws error : variable already defined] – (refer 2 in the image below)

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *