I wanted to return an object from an arrow function, but the code below was returning undefined
. I realized that the curly braces were being interpreted as beginning/ending the function body. What intrigues me is why a: 1
didn’t throw an error.
const foo = () => {a: 1};
foo();
// > undefined
The issue is that the parser sees a label called 'a' which belongs to the expression statement '1'. Since there's no return statement at all, the returned value is always undefined.
If you wrap the body inside '()' you'll see your object being returned, see below.
const foo = () => ({a: 1});
console.log(foo());
Edit: By adding the parentheses you are forcing the parser to treat the object literal as an expression so that it's not treated as a block statement.