jkschneider jkschneider - 1 year ago 48
Javascript Question

ECMAScript6 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 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?


You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. Next 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.