Home > Web Front-end > JS Tutorial > Can Variable Shadowing Occur in JavaScript with Different Scoped Variables of the Same Name?

Can Variable Shadowing Occur in JavaScript with Different Scoped Variables of the Same Name?

Linda Hamilton
Release: 2024-10-24 10:35:02
Original
700 people have browsed it

Can Variable Shadowing Occur in JavaScript with Different Scoped Variables of the Same Name?

Can you clarify variable shadowing using a basic JavaScript example?

Variable shadowing is a concept in JavaScript where a variable defined in a specific scope overrides another variable with the same name that is declared in a wider scope. Here's a basic example to illustrate:

Consider the following code snippet:

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

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

showMoney("100");</code>
Copy after login

In this example, there are two variables named currencySymbol. The global variable currencySymbol is initially set to "$". Inside the showMoney function, a new variable with the same name is declared and set to "€".

When the showMoney function is called, the local variable currencySymbol shadows the global variable with the same name. This means that the code within the function will use the local value of "€" for currencySymbol, overriding the global value of "$".

Consequently, when the line console.log(currencySymbol amount) is executed, it will print "€100" to the console. This is because the local variable currencySymbol is being used within the showMoney function, overriding the global variable.

Is this an example of variable shadowing?

Yes, this is a clear example of variable shadowing. The local variable currencySymbol within the showMoney function overrides the global variable with the same name, resulting in the function using the local value of "€" instead of the global value of "$".

The above is the detailed content of Can Variable Shadowing Occur in JavaScript with Different Scoped Variables of the Same Name?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template