DEV Community

Cezar Augusto Mezzalira
Cezar Augusto Mezzalira

Posted on

1

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay