Why would I do function() and not function blah()?

Today I got asked the question:

In JavaScript (the best language) what is the difference between these two:

function() { ... }
// and
function blah() { ... }

The first is an anonymous function.

The second is a named function.

Anonymous functions are one time deals.

Named functions can be used as many times as needed. Even zero times.

An example of an anonymous function:

[1,2,3].map(n => n + 1);

The function (n) => n + 1 is anonymous. It has no name.

But you could define it as a named function:

const addOne = (n) => n + 1;

And then you could repeat the map with the named function:

[1,2,3].map(n => addOne(n));
// or more simply,

And likewise you could use the function again and again:

const incremented = addOne(0); // 1
const again = addOne(incremented); // 2
const third_time = addOne(5); // 6

Even if your function is a one-and-done deal, naming functions can help you better explain your code to others (or yourself 5 minutes from now).

As soon as you name an anonymous function, it is no longer anonymous.

And that’s all I have to say about that.

Published by

Code Review

CodeReviewVideos is a video training site helping software developers learn Symfony faster and easier.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.