3

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?

raina77ow
  • 103,633
  • 15
  • 192
  • 229
grahamrhay
  • 2,046
  • 4
  • 19
  • 29
  • When in doubt, you could always feed this to babel and see what it transpiles it into. –  Dec 25 '15 at 13:48

1 Answers1

6

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 1
    In fact, `{ a: 2 }` is a block as well – vkurchatkin Dec 25 '15 at 12:45
  • @vkurchatkin In fact, it's not treated as a code block (otherwise it'd have been evaluated to `2`, `a:` considered as a label), but as a function's body. That's important distinction - and I admit I didn't know about it. Live and learn. ) – raina77ow Dec 25 '15 at 13:02