WitVault WitVault - 4 months ago 8
Javascript Question

How to return anonymous object from one liner arrow function in javascript?

I recently switched to es6 and started using arrow functions all over my code.
While refactoring I came across below code

data.map(function(d) {
return {id: d.id, selected: bool};

I changed above code to this -

data.map((d) => {id: d.id, selected: bool});

But I was getting error from above code. I don't know what is wrong here?
I know that If there is no block of code then there is implicit return provided by arrow function.

But don't know how to return empty object or anonymous object with some properties initialized ?


What is wrong if I do it in this way? Just for curiosity sake.

data.map((d) => new {id: d.id, selected: bool});


Put parens around the object initializer:

data.map((d) => ({id: d.id, selected: bool}) );

Parentheses have no effect on the value of the expression inside them, but they do have the syntactic effect of eliminating the ambiguity of the first token of the contained expression. Without the parentheses, the JavaScript parser has to decide whether the { token means "Here starts a function body" or "Here starts an object initializer." It always chooses the former (that is, a block of code).

Introducing the parentheses, therefore, eliminates the confusion: the only thing that a leading ( can mean is "here comes an expression", so that { inside the parentheses can only be "here comes an object initializer." (You can't drop a block of code in the middle of an expression, in other words; if you try, then you'll get a syntax error.)