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");
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With