Claudio
Claudio

Reputation: 5980

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?

Upvotes: 6

Views: 824

Answers (5)

AngusC
AngusC

Reputation: 628

There's a bit more too it than Alex said (even though he just referenced my article - thanks!).

If the code sequence was in the sequence it appears, "var myVar" would not get hoisted (or rather its hoisting would have no effect) because "window.myvar = 150" is defined first (moreover this wouldn't explain why the first example worked and the second one only failed in IE)

It looks like the second script is (somehow) loading before the first one - but only in IE8. You can simulate switching the tag sequence and you will see undefined alert in all browsers

var myvar;

if (false) {
  myvar = 3;
}

alert(myvar)

window.myvar = 150;

Upvotes: 2

qwertymk
qwertymk

Reputation: 35274

That's because since javascript does scope based on function levels, your code computes/compiles/equivalent to the following:

<script>

window.myvar = 150;

</script>

<script>
var myvar;

if (false) {
  myvar = 3;
}

// This will popup "undefined"
alert(myvar)

</script>

Upvotes: 3

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

I am for hoisting, as alex said. The compiler sees that you define myvar in your block (var myvar inside if) and hoists the previously known myvar. I am not sure, whether it is bug or feature, though.

Upvotes: 0

kirb
kirb

Reputation: 2049

This doesn't happen to me in iOS Safari on 4.3.1, so it might be a bug in IE. However, @alex's answer may also be true as well. Ad@m

Upvotes: 0

alex
alex

Reputation: 490243

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.

Upvotes: 3

Related Questions