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

I recently switched to es6 and started using arrow functions all over my code. While refactoring I came across below code {
   return {id:, selected: bool};

I changed above code to this - => {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. => new {id:, selected: bool});



Put parens around the object initializer: => ({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.)


Hi I think you need to add paranthesis to return object literal

// Parenthesize the body to return an object literal expression: params => ({foo: bar})



You can also use => {
    return {id:, selected: bool}
} );


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.