0

What is the difference between

settings = {
  edit: function (key, value) {
    return anotherFunction(key, value) {
      return value * 2;
    };
  }
};

and

settings = {
  edit: function edit(key, value) {
    return anotherFunction(key, value) {
      return value * 2;
    };
  }
};

?

Adam S
  • 509
  • 10
  • 24
  • You can refer to itself in the second function body – zerkms Jan 12 '14 at 04:42
  • Checkout http://kangax.github.io/nfe/ – user229044 Jan 12 '14 at 04:45
  • possible duplicate of [What is the difference between a function expression vs declaration in Javascript?](http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip) – Barmar Jan 12 '14 at 04:46

3 Answers3

3

There's no difference when executing.

However, in the second case (named function), you can call the function recursively easier because it has a name.

For example, with a named function you can do:

fact: function factorial(n) {
     if(n == 0) return 1;
     return n * factorial(n-1);   //You can do this with a named function easily
  }

Without a name, this would be tricky.

Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
1

The essential difference is better debugging. In your developer tools, the named function in your second example will appear as edit in a backtrace; your first example will appear as anonymous. This can be extremely confusing when you're 10 function deep, and they are all called anonymous.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • This is a very good observation. I'm trying to analyze Ghost.js to see how a node application works and this might be the best reason the functions are named. – Adam S Jan 12 '14 at 04:55
  • 1
    It really is. Everybody talking about recursion has missed the point. You don't need a *named* function to recurse, you just need a variable referencing the function. You can still recursively call an anonymous function this way. – user229044 Jan 12 '14 at 05:07
0

There are three reasons to give a function an inherent name. The first is that everyone does it. It's what everyone is used to.

function factorial(n) {
    var accum = 1, i;
    for (i = 1; i <= n; i++) {
        accum *= i;
    }
    return accum;
}

The second is to understand stack traces better, as @meagar wrote.

The third is to let you write call functions recursively.

var factorial = function(n) {
    var a = 1;
    return (function factRecursive(k, a) {
        if (k >= 2) {return factRecursive(k - 1, k * a)}
        else        {return a;}
    })(n, a);
}
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29