Is this an example of variable shadowing in JavaScript?

Viewed 40423

I learnt about the term variable shadowing in Eloquent Javascript (Chapter 3), but I am trying to understand a precise, basic example of the concept.

Is this an example of shadowing?

var currencySymbol = "$";

function showMoney(amount) {
  var currencySymbol = "€";
  console.log(currencySymbol + amount);
}

showMoney("100");

6 Answers

We cannot define a variable more than once. But we can define in different scopes.

let name="tara"
if(true){
  let name="ali"
  if(true){
    console.log(name)
  }
}

variable shadowing is when a variable in a local scope uses its value instead of a variable in a parent scope.So the local variables value is shadowing over the parents.

in the above code there are two name variables defined but they are not defined in the same scope. so console.log(name) will check the local scope if it finds the name variable it uses it, if not it checks parent scope once finds it, it uses that one so it does not go the root.

var role = "Engineer";
console.log(role);

function displayRole(){
    role = "developer";
    console.log(role);
}

displayRole();
console.log(role);

Notice how the last line of code (console.log) prints developer yet it’s not inside the function scope. This is a good example of shadowing where by the role variable in the global scope has been overwritten by the role in the function scope.

To avoid shadowing, the variable in the function scope should be declared using the var keyword so that it becomes accessible to the function only.

Yes, this is a good example of shadowing. A global scope variable is said to be shadowed by a block scope variable when both have the same name. This is happening in your code and the block scope is shadowing the global scope.

Related