Variable Shadowing in JavaScript

In javascript, when variable in inner scope is defined with the same name as variable defined in outer scope, inner scope variable shadows outer scope variable. This is called variable shadowing.

Shadowing prevents inner scope from accessing variable defined in outer scope

Let me illustrate with an example.

let x = 3;

function add(num){
  let x = 2;
  return num + x;
}

add(8);

In above code, variable x is declared  in global scope(outer scope) and re-declared inside the function.

What value will be returned if function add (with argument eight) is invoked?

Answer is 10. NOT 11

This is because global scope variable x is shadowed by function scope variable x when we call function add.

Does this mean global variable gets overwritten?

No. In global scope  the value of variable x is still 3.

Javascript creates new variable x in function scope. It does not overwrite global variable x.

If you console log variable x in global environment, it will return 3.

let x = 3;

function add(num){
  let x = 2;
  return num + x;
}
add(8); // 10
console.log(x)  // 3

To avoid error/confusion

  • Check at what scope your code is running. (Global, function, block)
  • Check where the variable was declared.