2

I have the code below:

//anonymous function expression
var a = function() {
    return 3;
}

//named function expression
var a = function bar() {
    return 3;
}

So, what is the different between them ? (technical, usage)

  • 2
    No specific difference, but using named functions can improve the readability of stacktraces in the event of a crash – Simon H Sep 09 '15 at 07:51
  • possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – mayank Sep 09 '15 at 07:54

1 Answers1

3

The main differences are

  • You can inspect the function name (for example stack traces are more readable)
  • The function can be recursive

Note that a function like

var fibo = function(n) {
    return n<2 ? 1 : fibo(n-1) + fibo(n-2);
};

is not really recursive as its body will call whatever fibo is bound to at the moment of the call (so it will not call itself if fibo is later assigned to something else). The version

var f = function fibo(n) {
    return n<2 ? 1 : fibo(n-1) + fibo(n-2);
};

is instead really recursive and will keep calling itself no matter what f is later bound to.

6502
  • 104,192
  • 14
  • 145
  • 251