Friday, May 17, 2024
140
rated 0 times [  145] [ 5]  / answers: 1 / hits: 149436  / 9 Years ago, fri, february 27, 2015, 12:00:00

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?


More From » ecmascript-6

 Answers
58

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


[#67639] Thursday, February 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alorac

Total Points: 262
Total Questions: 82
Total Answers: 97

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
alorac questions
Sat, Oct 10, 20, 00:00, 4 Years ago
Tue, Sep 22, 20, 00:00, 4 Years ago
Wed, Jul 1, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Sun, May 17, 20, 00:00, 4 Years ago
;