{ return {foo: "bar"}; }。如果箭头函数返回的不是对象,则 {} 和 return 是不必要的,例如:p => "foo"。p => {foo: "bar"} 返回 undefined......" /> { return {foo: "bar"}; }。如果箭头函数返回的不是对象,则 {} 和 return 是不必要的,例如:p => "foo"。p => {foo: "bar"} 返回 undefined......"> { return {foo: "bar"}; }。如果箭头函数返回的不是对象,则 {} 和 return 是不必要的,例如:p => "foo"。p => {foo: "bar"} 返回 undefined......" />
ChatGPT解决这个技术问题 Extra ChatGPT

ECMAScript 6 arrow function that returns an object

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

That means I can’t write p => {foo: "bar"}, but have to write p => { return {foo: "bar"}; }.

If the arrow function returns anything other than an object, the {} and return are unnecessary, e.g.: p => "foo".

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

A modified p => {"foo": "bar"} throws SyntaxError: unexpected token: ':'”.

Is there something obvious I am missing?

I'm not clear when to use return keyword and when not to use it, JS being very very flexible creates loads of bugs for new users of this language. I wish it was as strict like "Java" language

s
str

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


I'm curious why the parens make a difference.
@wrschneider because without parens js parser thinks that its a function body, not an object, and foo is a label
@wrschneider more specifically, in terms of AST nodes, using parentheses denotes an expression statement, in which an object expression can exist, whereas by default, curly braces are interpreted as a block statement.
No idea why this works, but if you want to use the value of p as key for the object literal, this is how you do it: p => ({ [p]: 'bar' }). Without the [], it'll either be undefined or literally the letter p.
@DanMan It's called computed properties and it's a feature of object literals.
P
Petr Odut

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!
}

Labels are such a seldom used and esoteric feature. Do they REALLY have any value? I feel like they should be deprecated and eventually removed.
@Kenmore See stackoverflow.com/questions/55934490/… - backwards compatibility. Browsers will refuse to implement a feature which breaks existing sites
@Kenmore you can exit from nested loops if they are labeled. Not often used but definitely useful.
P
Paul McBride

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


why we don't have to use return keyword inside parenthesis ?
Because p => ({ foo: 'bar' }) is transpiled into p => { return { foo: 'bar' }; }. It's a shorthand syntax.
Arrow functions implicitly return the expression on the right side of the arrow. eg p => p * 2 will return the result of p * 2. The exception to this rule is when the expression on the right side is wrapped in curly braces, then you have to return yourself.
R
Rusty

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

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

But if you want to have multiple statements then you can use the following syntax:

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

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions


x
xgqfrms

ES6 Arrow Function returns an Object

the right ways

normal function return an object


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

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

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

(js expressions )


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

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

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

explain

https://user-images.githubusercontent.com/7291672/63484861-ba0bf480-c4d3-11e9-950e-e22613ef25f6.png

refs

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

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


S
SirtusKottus

You can always check this out for more custom solutions:

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

This won’t even return a new object. The object you create there is discarded. This has little to do with this question.