ECMAScript 6 arrow function that returns an object

后端 未结 6 2258
花落未央
花落未央 2020-11-21 05:24

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 ambigui

6条回答
  •  萌比男神i
    2020-11-21 06:06

    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

提交回复
热议问题