2

For example:

module.exports = {
  myLibraryFunction: function myLibraryFunction() {
    ...
  }
}

The disadvantage is obvious. It's not very DRY, which means it can easily become out-of-sync if you're not careful. It also makes your code a little more verbose.

So what are the advantages? Is the tradeoff worth it?

Joe
  • 16,328
  • 12
  • 61
  • 75
  • The main advantages of returning named functions are that it's easier to debug. If you don't name them, in my experience, the debugger shows that there was an error in an anonymous function. That can be highly dependent on how you handle errors in your module, though. –  Feb 05 '15 at 20:27

1 Answers1

1

I use this approach when writing JS libraries. The largest advantage is that tools like the Chrome debugger will have a definite name for your function as opposed to either "anonymous" or some name composed of the function path based on the variable names containing the function. If, however, you don't care about having method names when debugging, then it really comes down to a matter of taste. If you were to minify the resulting JS code, naming elements like that would get stripped out anyway.

As far as to how DRY this approach is, consider that the repeated names occur right next to each other. A quick copy & paste is all it takes to keep them in sync. It would be nice if a JS included a feature that causes a function to be named according to the variable it has been assigned to at the point of creation (or at least the ability to dynamically re-assign the function's name). Sadly, however, this is the only way JS allows for us to name these otherwise anonymous functions.

Arkain
  • 918
  • 6
  • 10