ECMAScript6 arrow function that returns an object

2018-12-31 02:58发布

When returning an object from an arrow function, it seems that it is necessary to use an extra set of {} and a return statement because of an ambiguity in the grammar:

p => { return { foo: 'bar' } }

If the arrow function returns anything else, the {} and return are unnecessary, e.g.:

p => 'foo'

Is there something obvious I am missing?

3条回答
高级女魔头
2楼-- · 2018-12-31 03:30

You may wonder, why the syntax is valid (but not working as expected):

var func = p => { foo: "bar" }

It's because of JavaScript's label syntax:

So if you transpile the above code to ES5, it should look like:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}
查看更多
浮光初槿花落
3楼-- · 2018-12-31 03:32

If the body of the arrow function is wrapped in curly braces, it is not implicitly returned. Wrap the object in parentheses. It would look something like this.

p => ({ foo: 'bar' })

By wrapping the body in parens, the function will return { foo: 'bar }.

Hopefully, that solves your problem. If not, I recently wrote an article about Arrow functions which covers it in more detail. I hope you find it useful. Javascript Arrow Functions

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 03:35

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

查看更多
登录 后发表回答