For more tips like this, sign up to the weekly newsletter!
Return an object literal from an arrow function
Arrow functions can have a regular body, just like a traditional function with a block and a return
statement.
This function returns 5:
const f1 = () => {
return 5;
};
This way, they can also return an object literal, just like any other function:
const f2 = () => {
return {
p: 5
};
}
But the block itself is optional if all it contains is a return
statement, making the syntax more concise:
const f1 = () => 5;
But how to return an object literal when its declaration also uses curly braces, just like the block?
Parenthesize the literal to return an object:
const f3 = () => ({
p2: 5
});