Have you ever seen this strange IE IE behavior / error?

Ok, this is driving me crazy:

There are no problems in the first example:

<script> window.myvar = 150; if (false) { var myvar = 3; } // This will popup "150" alert(myvar) </script> 

Now, with TWO script elements:

 <script> window.myvar = 150; </script> <script> if (false) { var myvar = 3; } // This will popup "undefined" alert(myvar) </script> 

Tested with IE8.

Do you know, why?

+6
source share
5 answers

Inside the second example, in your second script block, myvar was raised (by specification) up to the containment area. Remember that JavaScript does not have a block scope, but only a scope.

Therefore, var myvar (the interpreted value of hoist) will cause myvar be undefined when alert() looks at myvar on VariableObject .

+4
source

This is because, as javascript makes the scope based on function levels, your code computes / compiles / is equivalent to the following:

 <script> window.myvar = 150; </script> <script> var myvar; if (false) { myvar = 3; } // This will popup "undefined" alert(myvar) </script> 
+3
source

There's a bit more than Alex said (although he just referred to my article - thanks!).

If the code sequence was in the sequence, it appears, "var myVar" will not rise (or rather, raising it will have no effect), because "window.myvar = 150" (moreover, this does not explain why the first example worked, and the second - only in IE)

It seems that the second script is loading (somehow) to the first, but only in IE8. You can simulate switching tag sequences and you will see an undefined warning in all browsers

 var myvar; if (false) { myvar = 3; } alert(myvar) window.myvar = 150; 
+1
source

This does not happen to me in iOS Safari 4.3.1, so it could be a bug in IE. However, @alex's answer may also be true. Ad @ m

0
source

I am for the rise, as Alex said. The compiler sees that you define myvar in your block ( var myvar inside if ) and raise the previously known myvar . I am not sure if this is a bug or function.

0
source

Source: https://habr.com/ru/post/892017/


All Articles