Archive for the 'ECMA' Category

Did you know that JS can be weird sometimes?

Of course you did, otherwise you wouldn’t read this! Anyway, I found this little easter egg in Javascript land:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function test(){
    var privateVar = 10;
    function tryXs(){
        if (false) {
            var privateVar = 5;
        }
        alert(privateVar);
    }
    this.callme = function(){
        tryXs.call(this);
    }
}
 
var oTest = new test();
oTest.callme();

Now what do you think what will the alert() show us? UNDEFINED! Now why would that be???
Well, apparently the ‘var’ in

1
2
3
if (false) {
    var privateVar = 5;
}

screws things up for us; even though the if-statement is evaluated to FALSE at all times, thus never executing the statement body (’var privateVar = 5′). Reasonably, you’d expect the alert dialog to display the value ‘10′, but apparently it still parses the body of the if-statement and pulls a string of the variable scoping rules.
Want to hear something even more weird? It’s consistent behavior! This occurs in all major browsers (I tested IE 6, FF 3.0.1, Opera 9.51 and Safari 3.1.2) and the alert shows ‘10′ when you remove the ‘var’ from ‘var privateVar = 5′. That actually makes sense again!

I’m quite interested to see and hear if anyone can give me an explanation for this behavior, because I probably lack the skill(s) to see any practical use in this ‘feature’ ;).
Does anyone else know a weird Javascript nugget like this?