JavaScript: The beauty of arrow functions

Richard Moss
3 min readSep 12, 2017

--

Arrow functions are an awesome ES6 language feature for a number of reasons, but we believe there are 3 key reasons they really shine:

  1. They are more concise
  2. They allow for implicit returns
  3. They get their “this” value from the context, meaning it comes from the caller

Let’s look at some ES5 vs ES6 code:

In the above code example we compare the ES5 and ES6 way of grabbing some values from an array of objects.

More Concise

The most striking thing is the amount of code, less code means less probability of introducing errors. Secondly it’s obvious that our arrow function has improved readability here, it’s also more declarative. Being concise and declarative with code is especially important when working in teams, it saves time and improves outcomes.

Implicit returns

The ability to return values implicitly builds upon the first point, we no longer need to add extra syntax such as the {} and return keyword if they are not needed. This allows for one-line manipulation of arguments, as we saw in our code example above where we return “animal.name” implicitly:

animal => animal.name

“This” value from the context

What will we see in our console when we execute fn() ?

The answer is we will see the Window object, because the context here is the Window.

What will we see when we execute obj.fn() ?

….

We will see the object, because the context here is the object. So context is simply the one who is calling the function.

If this isn’t clear, have a play with the code yourself here: https://jsbin.com/xoqopadeyo/edit?js,console

So why is getting the “this” value from the context useful?

Before we had to bind our functions explicitly to make sure they had the right “this” value:

We can of course continue doing this, but now we have a more concise way of doing the same thing:

Summing up

Using arrow functions allows us to use a more concise and declarative syntax while eliminating the need for us to bind them explicitly. There are of course a few more things to know about arrow functions which are beyond the scope of this post. However, these are the most important and relevant reasons to use them and what we believe makes them really special :-)

--

--