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;
    };
  }
};

?

3

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

Err, without a name, it'd be pretty easy: this.fact(). You can easily call a function without naming it: var x = function() { x() }.
@meagar What if the function isn't part of an object?
var x = function() { x() }
In this case callback(function f(n){ f(...); }); it's much easier with a named function (the other option(s) would be harder)
"Much" easier is pretty subjective; f = function () { return f(...); }; callback(f);
|
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.

2 Comments

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.
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.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.