Anonymous functions Vs. ES2016’s arrow functions

When coming from a verbose and strictly typed language such as Java, understanding the implicit workings of Javascript can sometimes feel like black magic. Using ES2016 syntax of so calledĀ arrow functions can make code more readable and compact. Since Java 8 the concept of arrow functions exists, but Java calls them Lambda expressions.
Below examples of Javascript arrow functions are taken from a React context and some of the syntax is React specific. The syntax shown goes from original Javascript to ES2016 arrow function and lastly an implicit version of theĀ arrow function (without the arrow).

Original JS

The original anonymous function call is verbose and will tell you everything about what is going on. When submitting the form a function will be called with an event as an argument. This argument will then be used in another function to handle the form submit. Pretty straightforward but the code tends to get a bit cluttered.

Arrow function
onSubmit={event => this.onFormSubmit(event)}

When instead using the ES2016 arrow function the code is more compact and in my view more readable. The anonymous function is implicit by just showing the argument event. This works with more arguments, but then the arguments would be written as (arg1, arg2). The => notation basically means given prefixed argument do this. So the argument being the event in this case, will be given to the next function as an argument to handle the form submit.

Implicit arrow function

An even more implicit version of the arrow function exists but it can only be used whenever there is only one argument to be passed forward. In this case the argument is implicitly placed within a function that takes only one argument. This can be done since there can be no misunderstanding to what argument is to be passed.

All of these ways of writing is valid and is in this simple case only preferential. But if you’re going to use other functional components such as the then it is good to get familiar with the concepts. The last way is though a bit more implicit than I would have liked. Though it is compact and arguably neat, I can only imagine the headache someone new to a project would have trying to understand what the function does.

Leave a Reply

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