js variable declaration can hoist initialization not hoist

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          

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326396381&siteId=291194637