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
data
hoisted? I am seeing the console asundefined
so I presume that thedata
variable ishoisted
.Is variable hoisting only inside the function? In the above program, if the
data
is hoisted does that imply that thedata
variable hoisted even at global level?The above program prints the text
Hello
when I define the function without a variable. So is this referred to as function hoisting or is it global function?If the
var data = 15
is 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.