Hoisting variable declarations across script tags?

后端 未结 3 602
死守一世寂寞
死守一世寂寞 2021-01-20 16:25

I have the following code inserted into a html file:

相关标签:
3条回答
  • 2021-01-20 16:36

    Why? Because the second script is not considered when the first one runs. The behaviour you describe, declaring all variables first before executing code, applies only to every individual block of code.

    0 讨论(0)
  • 2021-01-20 16:42

    In the above code the <script> with console.log(myVar) is rendered first and the system looks for the myVar variable in the global and local scope. Since, the variable is not found till this point it raises, Uncaught ReferenceError: myVar is not defined error as var myVar = 1; is rendered in the next <script> block.

    <script>
      console.log(myVar);
    </script>
    
    <script>
      var myVar = 1;
    </script>

    But when you change the order of the <script> blocks to something like below then it will work

    <script>
      var myVar = 1;
    </script>
    
    <script>
       console.log(myVar);
    </script>

    0 讨论(0)
  • 2021-01-20 16:55

    MyVar is now defined in the scope of your second example (even though it might be in example 1). In your final block of code, myVar is declared. I highy reccomend reading about variable scope in JavaScript (and Java)

    0 讨论(0)
提交回复
热议问题