dotslash dotslash - 3 months ago 18
Javascript Question

Why are my JavaScript function names clashing?

I wrote the following script just to see what happens when a variable and a function that has a function assigned to it have their names clash:

var f = function() {
console.log("Me original.");
}

function f() {
console.log("Me duplicate.");
}

f();


The output I'm getting is "Me original." Why was the other function not called?

Also, if I change my original assignment to
var f = new function() {
, I get "Me original", followed by a TypeError saying
object is not a function
. Can someone please explain?

Answer

Function declarations are hoisted (moved to the top) in JavaScript. While incorrect in terms of parsing order, the code you have is semantically the same as the following since function declarations are hoisted:

function f() {
    console.log("Me duplicate.");
}
var f = function() {
    console.log("Me original.");
}


f();

Which in turn, with the exception of the function's name is the same as:

var f = function() {
    console.log("Me duplicate.");
}
var f = function() {
    console.log("Me original.");
}


f();

Which in turn, because of variable hoisting is the same as:

var f;
f = function() {
    console.log("Me duplicate.");
}
f = function() {
    console.log("Me original.");
}

f();

Which explains what you're getting, you're overriding the function. More generally, multiple var declarations are allowed in JavaScript - var x = 3; var x = 5 is perfectly legal. In the new ECMAScript 6 standard, let statements forbid this.

This article by @kangax does a fantastic job in demystifying functions in javascript