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
scriptblock,myvarhas 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 tomyvarbeingundefinedwhen thealert()looks upmyvaron the VariableObject.