ECMAScript 6 arrow function that returns an object

When returning an object from a function with an arrow, it seems that it is necessary to use an additional set {}and keyword returndue to the ambiguity in the grammar.

This means that I cannot write p => {foo: "bar"}, but I must writep => { return {foo: "bar"}; } p => { return {foo: "bar"}; }

If the arrow returns anything other than the object, then {}, and return, for example, it is not necessary: p => "foo".

p => {foo: "bar"}returns undefined.

The modified p => {"foo": "bar"}produces " SyntaxError: unexpected token: ' :'".

Is there something obvious I'm missing?

+572
source share
6 answers

. . :

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

- :

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

.

: MDN -

+1024

, ( ):

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

- JavaScript:

, ES5, :

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}
+57

, . . .

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

parens, { foo: 'bar }.

, . , Arrow, . , . Javascript Arrow

+15


const getUser = user => {return { name: user.name, age: user.age };};

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

  1. (JS )

const getUser = user => ({ name: user.name, age: user.age });

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

image

!

https://github.com/lydiahallie/javascript-questions/issues/220

https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript

+1

:

:

p => {foo: "bar"}

JavaScript , , .

:

, :

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

, :

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In the above example, the first set of curly braces opens a code block with several statements, and the second set of curly braces is for dynamic objects. In a code block with multiple arrow function statements, you must explicitly use return statements

See the Mozilla Docs for JS Arrow Function Expressions for more information .

0
source

You can always check this for more individual solutions:

x => ({}[x.name] = x);
-1
source

All Articles