var x = 5; // initialize x elem = document.getElementById("demo"); // find element elem.innerHTML = x + " " + y; // display x and y var y = 7; // initialize y
y outputs undefined because the variable declaration (var y) is hoisted, but the initialization (y = 7) does not, so the y variable is an undefined variable.
Example 2 is similar to the following code:
var x = 5 ; // initialize x var y ; // declare y elem = document . getElementById ( "demo" ); // find element elem . innerHTML = x + " " + y ; // display x and y y = 7 ; // set y to 7