ECMAScript 6 arrow function that returns an object

后端 未结 6 2140
花落未央
花落未央 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条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:00

    Issue:

    When you do are doing:

    p => {foo: "bar"}
    

    JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

    Solution:

    If your arrow function expression has a single statement, then you can use the following syntax:

    p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})
    

    But if you want to have multiple statements then you can use the following syntax:

    p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}
    

    In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

    For more details, check Mozilla Docs for JS Arrow Function Expressions

提交回复
热议问题