JavaScript Nuance

Tue, 27 May 2008

I would like to describe yet another JavaScript weirdness. Fortunately I didn’t face it before and was absolutely sure that function a(){} is equal to var a = function (){}.

I was wrong. There is a huge difference. Lets see the example:

var a = 5;
if (a == 5) {
    var b = function () {
        return "obvious";
    };
} else {
    var b = function () {
        return "never";
    };
}

if (a == 5) {
    function c() {
        return "expected";
    }
} else {
    function c() {
        return "surprise!";
    }
    function d() {
        return "how come?";
    }
}

alert(b());
alert(c());
alert(d());

You probably guessed; the output will be “obvious”, “surprise!” and “how come?”. This will be everywhere, but Firefox. If you define a named function it is defined in the current scope by runtime compiler will process it wherever it appears in the code. So beware of such a constructions and don’t forget to test in other browsers.

P.S. The other difference is that function c has a property name equal to “c”:

c.name == "c";
b.name == "";