Returning Objects from Arrow Functions in ECMAScript 6
In ECMAScript 6, when dealing with arrow functions that return objects, a syntax ambiguity arises. The following code throws an error:
p => {foo: "bar"}
To resolve this ambiguity, you must wrap the returning object literal in parentheses:
p => ({ foo: "bar" })
This forces the curly braces to be interpreted as part of the object literal, not the function body.
This extra step is not necessary for returning other non-object values:
p => 10 p => 'foo' p => true p => [1,2,3] p => null p => /^foo$/
The reasoning behind this syntax is likely to prevent accidental object creation. By requiring parentheses, it becomes more explicit that the function is intended to return an object.
Therefore, when returning an object from an arrow function, it is crucial to remember to wrap the object literal in parentheses to avoid syntax errors or unexpected behavior.
The above is the detailed content of How to Correctly Return Objects from ECMAScript 6 Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!