Home  >  Article  >  Web Front-end  >  What is Variable Shadowing in JavaScript?

What is Variable Shadowing in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 10:20:29543browse

What is Variable Shadowing in JavaScript?

Understanding Variable Shadowing in JavaScript through an Example

Variable shadowing, a concept in JavaScript, occurs when a variable declared within a narrower scope (e.g., function) overrides a variable with the same name declared in a wider scope (e.g., global scope).

Consider the following example to better understand this concept:

<code class="javascript">var currencySymbol = "$";

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

showMoney("100");</code>

In this example, we have a global variable named currencySymbol initially set to the dollar sign "$". However, within the showMoney function, we declare another variable with the same name, this time set to the euro sign "€".

When the showMoney function is invoked, the function's currencySymbol variable shadows the global variable of the same name. This means that within the function, the value of currencySymbol becomes "€", and the dollar sign from the global scope is temporarily hidden.

Consequently, when we log the value of currencySymbol within the function, it prints "€100", indicating the override. This demonstrates the effect of variable shadowing, where a variable declared within a narrower scope overrides a variable with the same name declared in a wider scope.

The above is the detailed content of What is Variable Shadowing in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn