简体   繁体   中英

Javascript Shadowing - Effect if you try to change an already existing global variable w/o using the VAR keyword

So, I understand that declaring a variable without the var keyword means it's declared in the global scope.

So in the 1st example below, Line 4 of the code changes the global variable person (which does not have the var keyword preceding it) from "Jim" to "Andrew."

var person = "Jim";

function whosGotTheFunc() {
   person = "Andrew";
}

person = "Nick";
whosGotTheFunc();
console.log(person);

And in the 2nd example, Line 4 of the code creates a separate local variable, also entitled person .

var person = "Jim";

function whosGotTheFunc() {
   var person = "Andrew";
}

person = "Nick";
whosGotTheFunc();
console.log(person);

However, what does Line 7 of both examples do? The line that says: person = "Nick";

The Treehouse quiz asks what is logged to the console. In example #1, Line 4 changes the global variable person to "Andrew" but then Line 7 does NOT affect that global variable (so the console logs "Andrew")... However, in example #2, after Line 4 creates a local variable, Line 7 does, in fact, change the value of the global variable from "Jim" to "Nick" (the console logs "Nick").

What I want to know is in the 2 examples, why the difference in behavior of Line 7: person = "Nick"???

The variable is modified in both examples. However, the call to whosGotTheFunc() is after the global modification, so in the first example, it overwrites the value of "Nick", leaving it at "Andrew".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM