Christine Christine - 6 months ago 9
Javascript Question

Hoisting and variable scope

Would someone help explain why the two snippets of code below print out different results? The difference can be found inside the conditional statement. In the first, there is a local variable assignment of 'Jack' to name. In the second, the same name 'Jack' is assigned but to the global variable name. My question is, if all else is the same, why should it change the outcome? Shouldn't the conditional boolean be evaluated first before even starting to interpret its body? For example, shouldn't the variable 'name' be evaluated as 'undefined' in both cases?? 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";
}
console.log(name);
}
users(); //outputs "Jack"


vs.

var name = "Paul";
function users () {
if (!name) {
name = "Jack";
}
console.log(name);
}
users(); //outputs "Paul"

Answer

Variable declarations hoist to the top of the execution context, in this case the function users. Rewriting these to show how it looks from the hoisted perspective often clears up any confusion

var name = "Paul"; 
function users () {
    var name;//<- hoisted variable declaration
    if (!name) {
        name = "Jack";
    }
    console.log(name);
}
users(); //outputs "Jack"

vs.

var name = "Paul"; 
function users () {
    if (!name) {//no hoisted variable declaration, uses global
       name = "Jack";
    }
    console.log(name);
}
users();  //outputs "Paul"

Execution contexts contain several key components, the most relevant here are the lexical environment and variable environment. I cover the differences between the two (and some brief history) in more depth if you are interested here: http://stackoverflow.com/a/32573386/1026459

Comments