Home  >  Article  >  Web Front-end  >  What is Variable Shadowing and How Does It Affect Variable Scope in JavaScript?

What is Variable Shadowing and How Does It Affect Variable Scope in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 09:59:29288browse

What is Variable Shadowing and How Does It Affect Variable Scope in JavaScript?

Variable Shadowing Example in JavaScript

In the realm of JavaScript, variable shadowing emerges as a fundamental concept. To grasp its essence, let's delve into an illustrative example.

Example Scenario:

Consider the following code snippet:

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

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

showMoney("100");</code>

Explanation:

In this example, we encounter two versions of the variable currencySymbol. The global variable currencySymbol is initialized with the value "$", while a local variable with the same name is declared within the showMoney() function and given the value "€".

When the showMoney() function is invoked, the local currencySymbol variable comes into existence and shadows the global variable of the same name. Within the function's scope, any references to currencySymbol will refer to the local variable.

Consequently, when the line console.log(currencySymbol amount); is executed, the output will be "€100", not "$100". This is because the local currencySymbol variable takes precedence over the global one within the function's scope.

Conclusion:

This behavior exemplifies variable shadowing in JavaScript, where a local variable can mask a variable with the same name in an outer scope. By understanding this concept, you gain a deeper comprehension of variable scope and the intricacies of JavaScript code execution.

The above is the detailed content of What is Variable Shadowing and How Does It Affect Variable Scope 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