Arrow functions are awesome. They bind
this lexically, and even allow implied
return when they only contain one expression.
Unfortunately, it’s easy to get it wrong. Imagine we wanted to return a result object instead of only the integer. Something I often see in code (and write too often myself) is:
The expected result probably is:
However, it will be
undefined instead. This is because the curly braces, we intended to use to create an object literal, open a new block and therefore we’d need to add an explicit return or parenthesis around the implicit return statement to get it to work.
That’s pretty nasty and often hard to spot.
Here’s two versions that would fix the error:
After making this error a couple of times and simply accepting the way to fix it, I began to ask why doesn’t it throw an error, which would make my life a lot easier. Since enclosing the statement in curly braces does not create an object literal, but opens a new block, there’s only the following function body left:
To showcase it a little bit better, here’s how the entire function would look like in es5.
Example by mdn: