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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With