Skip to content Skip to sidebar Skip to footer

Nodejs Arrow Function With Expression

According to the documentation, you can return an expression from an arrow function: (param1, param2, …, paramN) => expression // equivalent to: => { return expressio

Solution 1:

According to the docs, the body of fat arrow function can be written as either a single expression or a series of statements wrapped into {} (just as you write bodies of plain old functions).

The point is, if parser encounters { after the =>, it goes with the second option. Now, it doesn't matter whether or not you use empty object literal or full object literal (like { a: 2 } in the first edit of this answer) - it's never treated as object literal, only as a function's body.

And what happens if function doesn't have a return statement? Right - this function returns undefined. That's why you get three of those as result of map (both for => {} and for => { a: 2 }).

To get three empty objects instead, just wrap {} into (), like this:

[1,2,3].map(i => ({}));

... as it forces the parser to go with expression path.

Post a Comment for "Nodejs Arrow Function With Expression"