Look at the following snippet:
var fruit = "Orange";
echoThis();
function echoThis() {
alert(fruit);
var fruit = "Apple";
}
When I run this snippet, the alert of fruit is undefined. Why?
First I thought it has something to do with hoisting, that within a funciton, the JS engine "lifts" all var declarations to the top or something, but then I would expect the alert to display Apple, not undefined.
There's probably some elementary JS behaviour I'm unaware of. Anyone care to explain?
JS fiddle: https://jsfiddle.net/z37230c9/