Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
Jonathan Schneider Avatar asked Feb 27 '15 17:02

Jonathan Schneider


People also ask

How do you return an object from arrow?

The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.

Can we create object with arrow function?

Arrow functions cannot be used as constructors and will throw an error when used with new .

Can arrow function have return?

Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


2 Answers

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! } 
like image 28
Petr Odut Avatar answered Sep 28 '22 02:09

Petr Odut


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

like image 200
alexpods Avatar answered Sep 28 '22 02:09

alexpods