I am learning javascript hoisting and came across a scenario for which I need a bit more explanation. Below is the program that I have
test();
console.log("The value of data is "+data);
function test(){
console.log("Hello");
}
var data = 15;
If I run the above program in JsFiddle, I am getting the below output:
Hello
The value of data is undefined
Is the
datahoisted? I am seeing the console asundefinedso I presume that thedatavariable ishoisted.Is variable hoisting only inside the function? In the above program, if the
datais hoisted does that imply that thedatavariable hoisted even at global level?The above program prints the text
Hellowhen I define the function without a variable. So is this referred to as function hoisting or is it global function?If the
var data = 15is changed todata = 15, then I get the error:Uncaught ReferenceError: data is not defined. Why is it behaving differently than in case of function?
Please help me understand what I am missing here.