Understanding Variable Shadowing in JavaScript: A Basic Example
In JavaScript, variable shadowing occurs when a variable with the same name is declared in a narrower scope, effectively hiding the variable declared in a wider scope.
Consider the following code:
<code class="javascript">var currencySymbol = "$"; function showMoney(amount) { var currencySymbol = "€"; console.log(currencySymbol + amount); } showMoney("100");</code>
In this example, there are two variables named currencySymbol. The first is declared in the global scope, while the second is declared within the showMoney function. When the showMoney function is called, it creates its own currencySymbol variable, which shadows the global variable with the same name. Within the function, the function-scoped currencySymbol is used, resulting in an output of "€100", rather than "$100".
This behavior illustrates variable shadowing. The function overrides the global variable within its scope, creating a new instance of the variable with the same name. This technique can be useful for limiting the scope of variables and preventing unintentional variable collisions.
The above is the detailed content of Understanding Variable Shadowing in JavaScript: When Does Variable Scope Override?. For more information, please follow other related articles on the PHP Chinese website!