Home >Web Front-end >JS Tutorial >When Should I Use Parentheses or Curly Braces in ES6 Arrow Functions?

When Should I Use Parentheses or Curly Braces in ES6 Arrow Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 15:02:39774browse

When Should I Use Parentheses or Curly Braces in ES6 Arrow Functions?

Using Parenthesis or Curly Braces in Arrow Functions

In ES6, arrow functions provide a concise syntax for defining functions. However, one common confusion is the use of parenthesis or curly braces after the fat arrow (=>).

Single Value Return: Parenthesis

Parentheses are used when the arrow function returns a single value, such as:

const foo = (params) => (
    <span>
        <p>Content</p>
    </span>
);

In this example, the arrow function returns a JSX element. Since it's a single element, parentheses are used.

Multiple Line Code: Curly Braces

Curly braces are required when the arrow function executes multiple lines of code:

const handleBar = (e) => {
    e.preventDefault();
    dispatch('logout');
};

Here, the arrow function performs multiple operations, hence it uses curly braces.

Ambiguity with JSX

The parentheses in the following example may seem confusing because it uses JSX:

const foo = (params) => (
    <span>
        <p>Content</p>
    </span>
);

While it appears to use multiple lines, JSX is actually compiled to a single element, which is why parentheses are used.

Other Examples

For clarification, here are some additional examples:

const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
  "hello " + who + "!"
);
const d = (who) => (
  "hello "
    + who
    + "!"
);
const e = (who) => {
  return "hello " + who + "!";
};

These functions all return the same result, demonstrating the flexibility of using parenthesis or curly braces based on the number of executed lines.

Avoiding Parser Confusion

Parentheses can also be used around object literals to avoid the parser treating them as code blocks:

const x = () => {} // Does nothing
const y = () => ({}) // Returns an object

The above is the detailed content of When Should I Use Parentheses or Curly Braces in 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