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:
1 | function add(a, b) { |
All other ways, including ES2015's much-touted [Arrow functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) produce anonymous functions. One of these ways is:
1 | var add = function (a, b) { |
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
See the Pen Anon Func by Tarun Batra (@tbking) on CodePen.
Error stack using named function
See the Pen Named Func by Tarun Batra (@tbking) on CodePen.
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.
1 | add(1, 2); // => 3 |
But the following code won’t work.
1 | add(1, 2); // => Error |
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.
1 | $('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.
1 | $('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
️