简体   繁体   中英

JavaScript Variable hoisting without functions

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?

Your var x statement is hoisted to the top. Therefore the assignment to x happens after it's declared, and before the alert() .

The sample code in your linked reference that may be throwing you off is this:

var myvar = 'my value';

(function() {
  alert(myvar); // undefined
  var myvar = 'local value';
})();

That example is different from yours in this essential way: the initialization of the variable involved happens after the alert() , not before. When a var declaration is hoisted, the only part that's hoisted is the declaration itself, not the initialization. That little function above is interpreted as if it were written:

var myvar = 'my value';

(function() {
  var myvar;
  alert(myvar); // undefined
  myvar = 'local value';
})();

Your code has x = 5 right up at the top, so it's not the same situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM