what are arrow function expressions?

Arrow function expressions (also known as fat arrows) are anonymous function expressions which lexically bind the this value, all with a shorter syntax. Take a look at the following examples, which both do the exact same thing.

There is no denying that the syntax for the second example is more concise, but is it the best way to achieve this? On the surface it sounds great, but it comes at the cost of being less clear. This isn’t a good thing and I’m not the only one who thinks so either. Take a look at this recent post by Kyle Simpson, where he reiterates that clear code always trumps clever code.

a more complex example

Let’s look at a more complex example that we’re more likely to use in the real world. The following code will throw an error because the this.methodTwo call on line 12 has a different scope:

You can see that line 11 is equivalent to lines 11 – 13 in the previous example. Again, there is no doubt that this is more concise, but it is not as clear (at least to me) when scanning the code.

conclusion

To summarise, I think this serves as a good example as to why we should strive to write clear code over clever code. The clever way often requires the next developer to work harder to understand what is going on, which is time that could be spent solving problems.

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.