Why you should use named functions in JavaScript

JavaScript functions can be categorized into named or anonymous on the basis of the value of their name property. A named function can be declared as follows:

function add(a, b) {
  return a + b;
}
console.log(add.name) // => "add"

All other ways, including ES2015’s much-touted Arrow functions produce anonymous functions. One of these ways is:

var add = function (a, b) {
  return a + b;
}
console.log(add.name) // => ""

NOTE: If you tried the above code in Chrome Dev Tools, you would’ve noticed that the name of the function is “add” even in the case of anonymous function. That’s because modern-day interpreters are smart enough to recognize the name from the expression.


Now, what’s special about named functions?

Make sense with error stacks

Error and call stacks are a great help in debugging code. But the use of anonymous functions reduces the usefulness of the call stacks. We all have seen the infamous (anonymous) littered over the stack trace.

Of course, one can always look at the line number of the error, but with the ever-increasing pre-processing on the code (read Babel, WebPack, Browserify), this is not a reliable method.

Error stack using anonymous function

Error stack using named function

JavaScript ecosystem is already confusing as is and the developer can use as much help as she can get to make sense of the obscure errors.

Use methods before declaration

While interpreting code, JavaScript looks for statements starting with function keyword (i.e. named function expressions) and move them to the top. This is called Hoisting.

So practically, a named function is available even before it’s declared, making the following code valid.

add(1, 2); // => 3
function add (a, b) {
  return a + b;
}

But the following code won’t work.

add(1, 2); // => Error
var add = function (a, b) {
  return a + b;
}

Improves readability

It’s fairly difficult to understand a callback function’s purpose in first glance. That’s what makes callback hell the problem it is.Look at the following jQuery code.

$('form').submit(function () {
  // ...
});

The above code provides no information on what’s going to happen to the submitted form. Adding names to callbacks improves readability and acts as implicit documentation, as the following code does.

$('form').submit(function hitAPI () {
  // ...
});

Conclusion

In my opinion, there’s no reason one should not use named functions when possible. Most of the JavaScript style guides out there don’t give due importance to them. ESLint users can use func-names rule in their projects to require the use of named functions, and enjoy the benefits.

❤️ code


Originally published at tarunbatra.com.