nodejs arrow function with expression [duplicate]

2019-02-25 03:04发布

问题:

This question already has an answer here:

  • ECMAScript 6 arrow function that returns an object 3 answers

According to the documentation, you can return an expression from an arrow function:

(param1, param2, …, paramN) => expression
     // equivalent to:  => { return expression; }

but this doesn't seem to work as I would expect (nodejs 4.2.3)

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

Shouldn't the 2nd example return 3 empty objects? Or am I missing something?

回答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.