JavaScript documentation sates:
Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.
Now in my (actually it's a code snippet from W3Schools on the same subject) code I am not using functions:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript index</title>
</head>
<body>
<p id="demo"></p>
<script>
x = 5; // Assign 5 to x
elem = document.getElementById( "demo" ); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
alert( x );
</script>
</body>
</html>
The result of alert() is 5. Why isn't it undefined. From my understanding the line var x should be hoisted to the top and alert() should display undefined.
I read some more about this from: http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092
What am I not getting?
5alert()would showundefined? I don't follow your reasoning.