patternjavascriptCritical
ECMAScript 6 arrow function that returns an object
Viewed 0 times
objectarrowfunctionreturnsecmascriptthat
Problem
When returning an object from an arrow function, it seems that it is necessary to use an extra set of
That means I can’t write
If the arrow function returns anything other than an object, the
A modified
Is there something obvious I am missing?
{} 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?
Solution
You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:
You don't need to wrap any other expression into parentheses:
and so on.
Reference: MDN - Returning object literals
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
Code Snippets
p => ({ foo: 'bar' })p => 10
p => 'foo'
p => true
p => [1,2,3]
p => null
p => /^foo$/Context
Stack Overflow Q#28770415, score: 1470
Revisions (0)
No revisions yet.