Tri nguyen minh
Tri nguyen minh

Reputation: 129

Different between anonymous function expression and named function expression (JavaScript)?

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)

Upvotes: 2

Views: 55

Answers (1)

6502
6502

Reputation: 114481

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.

Upvotes: 3

Related Questions