Would someone help explain why the two snippets of code below print out different results?
The difference is inside the conditional statement. In the first, there is a local variable assignment of 'Jack' to name, and the conditional is truthy (meaning !name evaluates to true). In the second, the same name 'Jack' is assigned but to the global variable name, but the conditional is falsy (!name is false). My question is, if all else is the same, why would the first conditional be true and the second is false if what is changed is inside the conditional body?
My only explanation is that the body of the conditional is read by the JS interpreter first, which is how it determines whether name
is global/local, whether the variable declaration needs to be hoisted or not, and finally, the different name values logged.
Shouldn't the conditional boolean be evaluated first before even starting to interpret its body? Then in both cases, variable 'name' would be evaluated as 'undefined'... Any help would be greatly appreciated!
There are a few really good resources about hoisting/scope contexts but I'm not finding one that specifically answers this question.
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
var name = "Paul";
function users () {
if (!name) {
var name = "Jack"; //<== difference is here, *inside* conditional body
}
console.log(name);
}
users(); //outputs "Jack"
vs.
var name = "Paul";
function users () {
if (!name) {
name = "Jack"; //<== difference is here, *inside* conditional body
}
console.log(name);
}
users(); //outputs "Paul"