Returning Objects from Arrow Functions in ECMAScript 6
In ECMAScript 6 (ES6), arrow functions provide a concise syntax for defining functions. However, when returning an object from an arrow function, a common confusion arises due to a grammatical ambiguity.
The following code snippet will result in unexpected behavior:
p => {foo: "bar"}
This expression will return undefined instead of the expected object. To address this, an additional set of curly braces and a return keyword are required:
p => { return {foo: "bar"}; }
This approach ensures that the curly braces are interpreted as an object literal, not as the function's body.
However, this extra syntax can be cumbersome. Fortunately, a simpler solution exists. By wrapping the object literal in parentheses, the ambiguity is resolved:
p => ({ foo: 'bar' })
With this modification, the curly braces are clearly denoting the object literal, and the return keyword is not necessary. This technique can be applied to any other expression being returned by an arrow function, eliminating the need for additional syntax overhead:
p => 10 p => 'foo' p => true p => [1,2,3] p => null p => /^foo$/
By understanding the grammatical ambiguity and using the parentheses wrapping technique, developers can effectively return objects from arrow functions in ECMAScript 6.
The above is the detailed content of How to Correctly Return Objects from ES6 Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!