Questions on Javascript hoisting

While I was reading about Javascript hoisting, I tried the following. I am not sure why the first one and second one output differently. Thanks in advance. (I am not even sure that this is related to hoisting. )

var me = 1;
function findme(){
   if(me){
    console.log( me );//output 1
    }
  console.log( me ); //output 1
}
findme();

However the followings output undefined.

var me = 1;
function findme(){
 if(me){
    var me = 100;
    console.log(me); 
    }
  console.log(me); 
}
findme();
// undefined

Variable declarations get hoisted to the top of every function, but the value assignments stay where they are. So the second example is run like this:

var me = 1;
function findme () {
    var me;  // (typeof me === 'undefined') evaluates to true
    if (me) { // evaluates to false, doesn't get executed
        me = 100;
        console.log(me); 
    }
    console.log(me); 
}
findme();

The declaration of thee local variable in the if block in the second example is hoisted to the entire function.

Thus, me in the function always refers to the local variable, not the global.

However, the value of the variable is not hoisted, so it's always undefined and the if is never entered.


Hoisting of a var does NOT hoist the assignment, just the declaration. So it's being parsed like this:

function findme(){
  var me;
  if(me){
    me = 100;
    console.log(me); 
  }
  console.log(me); 
}

When the if statement runs, me is decalred local to the function, but is undefined (has no value). undefined is falsy so your condition is never true.

This is why it's customary to always declare your local variables at the top of functions, because that's where they go anyway, if you like it or not.