Why does local variable names take precedence over function names in JavaScripts?

Posted by fredrik on Stack Overflow See other posts from Stack Overflow or by fredrik
Published on 2012-10-31T10:51:19Z Indexed on 2012/10/31 11:00 UTC
Read the original article Hit count: 171

Filed under:

In JavaScript you can define function in a bunch of different ways:

function BatmanController () {
}

var BatmanController = function () {
}

// If you want to be EVIL
eval("function BatmanController () {}");

// If you are fancy
(function () {
    function BatmanController () {
    }
}());

By accident I ran across a unexpected behaviour today. When declaring a local variable (in the fancy way) with the same name as function the local variable takes presence inside the local scope. For example:

(function () {
    "use strict";

    function BatmanController () {
    }

    console.log(typeof BatmanController); // outputs "function"

    var RobinController = function () {
    }

    console.log(typeof RobinController); // outputs "function"

    var JokerController = 1;
    function JokerController () {

    }
    console.log(typeof JokerController); // outputs "number", Ehm what?
}());

Anyone know why var JokerController isn't overwritten by function JokerController? I tested this in Chrome, Safari, Canary, Firefox. I would guess it's due to some "look ahead" JavaScript optimizing done in the V8 and JägerMonkey engines. But is there any technical explanation to explain this behaviour?

© Stack Overflow or respective owner

Related posts about JavaScript