Wednesday, April 27, 2016

JavaScript Variable Hoisting Example


var message = "I am Global";

function sayHello(){
     //message is truthy
     if(message){
        console.log(message);
  }
}

//This function runs as expected
sayHello();



function sayHelloHoisting(){
  //The if block should not run as message has already been initialized and is not falsy
  if(!message){
  //variable declared inside if block
  var message = "I should not get displayed";
  console.log(message);
  }
}

//The message gets logged to the console!!
sayHelloHoisting();

-----------------------------------------------------------------

//what actually happens with variable hoisting
// a new message variable created inside function which is undefined(falsy)
function sayHelloHoisting(){
var message = undefined;
if(!message){
  message = "If not for variable hoisting, I should not display!!";
  console.log(message);
  }
}