DEV Community

Cezar Augusto Mezzalira
Cezar Augusto Mezzalira

Posted on

Why you should favour named functions in place of anonymous functions at callback

Hello there! It's your cap again!

Recently, when I learn more about functions in JavScript, I found something who get my attention. In this blog post from Dmitri Pavlutin, he explain why favour name function expressions in place of anonyumous functions at callbacks.

At first, it's a simple thing I said. But, I make a small experiment to test this behavior.

I created two functions, with same behavior: make a division by an undefined variable.

Let's check the first scenario, using anonymous function:
Anonymous function declaration

Here, I create an arrow function on map callback. When the function test has been executed, we can see an error stack with various :
Anonymous function error stack

It's a little bit hard to understand what happen.

So let's check the second scenario. We can watch the map callback function is named function expression declared as divide.

Named expression function

When the function has been executed, we can see after reference error the name of function has triggered the error:

Named expression function error

So, which scenario is easier to debug?

Imagine you have have this function called inside one, two, three levels of functions. Which one it's easier now?

My point here, after all of it: use wisely the named expression functions. It's a debug time saver and maintain your code cleaner.

Top comments (0)