Home > Web Front-end > JS Tutorial > Understanding Variable Shadowing in JavaScript: When Does Variable Scope Override?

Understanding Variable Shadowing in JavaScript: When Does Variable Scope Override?

Linda Hamilton
Release: 2024-10-24 18:30:49
Original
230 people have browsed it

Understanding Variable Shadowing in JavaScript: When Does Variable Scope Override?

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>
Copy after login

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!

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