Home >Web Front-end >JS Tutorial >Arrow Functions in ES6: Parentheses or Curly Braces – When to Use Which?

Arrow Functions in ES6: Parentheses or Curly Braces – When to Use Which?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 00:39:09537browse

Arrow Functions in ES6: Parentheses or Curly Braces – When to Use Which?

Arrow Functions: Parentheses vs. Curly Braces

Arrow functions in ES6 offer a concise syntax for defining functions. However, it can be puzzling when you encounter arrow functions with different formats, some with curly braces and others with parentheses.

Parentheses: Single Expression

Arrow functions with parentheses after the fat arrow return a single expression. The following example returns a span element:

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

Curly Braces: Multiple Expressions

In contrast, arrow functions with curly braces execute multiple lines of code. This format allows for more complex operations, such as updating state or handling events:

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

JSX and Multiple Lines

The example with foo may seem confusing because it uses JSX (JavaScript XML), which represents HTML elements. The code appears to span multiple lines, but it's actually compiled into a single element.

Additional Examples

Here are some more examples illustrating the difference:

const a = (who) => `hello ${who}!`; // Parentheses: Single expression
const b = (who) => (`hello ${who}!`); // Parentheses: Equivalent to (a)
const c = (who) => (...
  `hello ${who}!`...); // Curly braces: Multiple lines
const d = (who) => (
  `hello \
    ${who}!` // Curly braces: Multiple lines
);
const e = (who) => {
  return `hello ${who}!`; // Curly braces: Multiple lines with explicit return
};

Parentheses Around Object Literals

You may also encounter parentheses around object literals. This practice avoids confusing the parser, which may otherwise treat an object literal as a code block:

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

In summary, arrow functions with parentheses return a single expression, while those with curly braces execute multiple lines of code. Understanding this distinction is crucial for writing effective and readable ES6 code.

The above is the detailed content of Arrow Functions in ES6: Parentheses or Curly Braces – When to Use Which?. 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