sum = (a, b) => { a + b };
We have to discuss a little bit of JS here.
For the arrow function, there are two ways you can return a value, implicitly and explicitly. If you don’t provide a code block (no open curly brace) and it’s just an expression, the arrow function will just return whatever that expression evaluates to.
const squareIt = x => x*2;
Here, it evaluates x*x
and returns it.
But you opened with a curly brace so the arrow function goes into “explicit return” mode, expecting and actual return
. Since it sees no return
in the code block, it returns undefined
. We would have wanted something like this:
const squareIt = x => {
return x*2;
}
If your arrow function is small, an implicit return makes sense. If not, go explicit.
Since it’s related, there is a gotcha with arrow functions. If you want to return an object as an implicit return, you can’t do this:
const getNameObj = (firstName, lastName) => { first: firstName, last: lastName };
That is going to throw an error because it sees an open curly brace and assumes it is a code block and tries to interpret the innards as an expression. But if we wrap it all in parentheses, JS know that it is all an expression:
const getNameObj = (firstName, lastName) => ({ first: firstName, last: lastName });
That’s bound to come up eventually.