Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an example of variable shadowing in JavaScript?

I learnt about the term variable shadowing in Eloquent Javascript (Chapter 3), but I am trying to understand a precise, basic example of the concept.

Is this an example of shadowing?

var currencySymbol = "$";  function showMoney(amount) {   var currencySymbol = "€";   console.log(currencySymbol + amount); }  showMoney("100");
like image 918
fakeguybrushthreepwood Avatar asked Aug 10 '12 12:08

fakeguybrushthreepwood


People also ask

What is this variable in JavaScript?

In JavaScript, “this” variable is a variable that every execution context gets, in a regular function call. Every JavaScript function has a reference to its current execution context while executing, called this. Execution context means here means the manner of calling of functions.

What does shadowing mean ?/ P in JavaScript?

Shadowing: Now, when a variable is declared in a certain scope having the same name defined on its outer scope and when we call the variable from the inner scope, the value assigned to the variable in the inner scope is the value that will be stored in the variable in the memory space.

What is a shadowed variable in typescript?

Shadowing means declaring an identifier that has already been declared in an outer scope. Since this is a linter error, it's not incorrect per se, but it might lead to confusion, as well as make the outer i unavailable inside the loop (where it is being shadowed by the loop variable.)

How do you avoid variable shadowing?

How to avoid variable shadowing? To modify a global variable, and avoid variable shadowing python provides global keyword which tells python to use the global version of the variable, instead of creating a new locally scoped variable.


1 Answers

That is also what is known as variable scope.

A variable only exists within its containing function/method/class, and those will override any variables which belong to a wider scope.

That's why in your example, a euro sign will be shown, and not a dollar. (Because the currencySymbol containing the dollar is at a wider (global) scope than the currencySymbol containing the euro sign).

As for your specific question: Yes, that is a good example of variable shadowing.

like image 109
Madara's Ghost Avatar answered Sep 28 '22 17:09

Madara's Ghost