3

We've been discussing it for a while where I work and we didn't find an answer:

Does declaring a function like this:

function myFunction(){
  //...
}

Made a difference on the performances than doing it like this:

var func = function myFunction(){
  //...
}

If not, where is the difference ?

Axiol
  • 4,711
  • 7
  • 35
  • 43

3 Answers3

3

No, there is no difference in performance.

Strictly speaking the former is a normal "function declaration", and the latter is assigning a "function expression" to a variable, but at invocation time they're treated identically.

The most significant difference (and it doesn't affect performance) is that due to hoisting the function declaration will be accessible anywhere in scope, but in the version that uses a function expression the variable func will be declared but not usable until after the var func = ... line.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
1

The difference is that function with var is run-time definition, whereas other function is a parsing time definition for a script.

first example is a function declaration. This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later,

second snippet shows a function expression. This involves using the "function" operator to create a function the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function" because it does not have to have a name,

Function expressions can actually be seen quite often. A common pattern in web development is to “fork” function definitions based on some kind of a feature test, allowing for the best performance. Since such forking usually happens in the same scope, it is almost always necessary to use function expressions.

Have a look at Named function expressions demystified

Hemant Metalia
  • 25,838
  • 17
  • 67
  • 86
0

There should be no significant performance difference in those.

There is another difference in such function declaration, I believe you should have a read about function and variable hoisting in javascript.

test(); // "X"
function test() {
    console.log("X");
}

anotherTest(); // TypeError: undefined is not a function
var anotherTest = function () {
    console.log("Y");
}
Emil A.
  • 3,131
  • 4
  • 26
  • 43