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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With