Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t a colon in function body not throw an error in JavaScript?

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
like image 533
Eduardo Matos Avatar asked Nov 29 '25 20:11

Eduardo Matos


1 Answers

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.

like image 186
Adrian Avatar answered Dec 01 '25 10:12

Adrian