Yeah, you can elide the brackets and the return statement if the return value is a single expression.
That might read as gibberish, so as an example:
const add = (a, b) => {
return a + b;
}
Theres just a single expression there, so you can write it like:
const add = (a, b) => a + b;
If there wasn’t just a single expression, you need the brackets and the return
const add = (a, b) => {
console.log(`a is ${a}`, `b is ${b}`);
return a + b;
}
It’s a quality of life thing (makes it a bit less onerous to write stuff like someListOfNumbers.map(v => v * 2)
), but it’s easy to trip up on it.
For comparison, it’s very similar to if
statements or for
or while
loops:
// Single expression, can miss out brackets:
if (someCondition) doSomething();
// Multiple expressions, need the brackets:
if (someCondition) {
doSomething();
doSomethingElse();
}
Also, just for future reference, another thing that trips people up a lot is returning objects. The syntax for objects ({}
) is the same as it is for blocks, so if you write
const giveMeAnObject = () => {
userName: "DanCouper"
};
It won’t work, because it’s going to think it’s a function without a return value, you need to write:
const giveMeAnObject = () => ({
userName: "DanCouper"
});
Which will work fine