Home >Web Front-end >JS Tutorial >How Do I Correctly Return Objects from ES6 Arrow Functions?

How Do I Correctly Return Objects from ES6 Arrow Functions?

DDD
DDDOriginal
2024-12-19 07:36:10961browse

How Do I Correctly Return Objects from ES6 Arrow Functions?

Returning Objects from Arrow Functions in ECMAScript 6

In ECMAScript 6 (ES6), arrow functions simplify code readability by providing a concise syntax for arrow function returns. However, when returning objects from arrow functions, some ambiguity arises, leading to the requirement of enclosing the object literal in braces and explicitly using the return keyword.

Ambiguous syntax occurs when omitting the braces. For instance, p => {foo: "bar"} signifies the function body rather than an object return. To resolve this, parentheses must enclose the object literal: p => ({foo: "bar"}).

When returning non-objects, parentheses are unnecessary. Examples include:

  • p => 10
  • p => 'foo'
  • p => true
  • p => [1,2,3]
  • p => null
  • p => /^foo$/

The MDN documentation clarifies this concept in its section on returning object literals. By enclosing the object literal in parentheses, the parser can correctly interpret the intended return value.

The above is the detailed content of How Do I Correctly Return Objects from ES6 Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn