Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would assigning a function to a var be different than simply defining it? [duplicate]

Tags:

javascript

So I'm just about to add a new function to our every growing list of global ones (sigh) and noticed the last user used a variable assignment over simple function a(){}.

function aFunction(){
    return null;
}

var bFunction = function(){
    return null;
}

I created a test to see if it made a difference; It does, but a conflicting one. (chrome favours the simple function, while firefox the variable assignment).

Firefox: Function create (90+% slower) / Create with variable assignment (fastest)

Chrome: Function create (fastest) / Create with variable assignment (70+% slower)

I understand it's trivial but is there any reason for the discrepancy and is there a preferable way of doing this?

like image 708
Phil Cooper Avatar asked May 28 '13 14:05

Phil Cooper


1 Answers

One difference between the two is how they behave in the browser.

Defining the function in the first case will work no matter where in the code that it is called. In the second case, if you attempt to call it before it is defined an error will be thrown.

This answer explains in better detail: What is the difference between a function expression vs declaration in JavaScript?

So which way that is preferable would depend on use case.

As to difference in browser speed, I imagine that that is due to differences in how the browsers are parsing the javascript.

like image 145
Schleis Avatar answered Sep 18 '22 06:09

Schleis