Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have you ever seen this weird IE JavaScript behaviour/bug?

OK, this is driving me crazy:

First example, no problem:

<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.

Have you any idea why?

like image 277
Claudio Avatar asked Jul 05 '11 10:07

Claudio


1 Answers

Inside the second example, in your second script block, myvar has been hoisted (as per the spec) to the top of the containing scope. Remember JavaScript does not have block scope, only function scope.

Therefore, var myvar (the hoisted definition that is interpreted) is going to lead to myvar being undefined when the alert() looks up myvar on the VariableObject.

like image 194
alex Avatar answered Nov 04 '22 05:11

alex