Arrow Functions: When to Use Parentheses and Curly Braces
Arrow functions, introduced in ES6, are concise syntax for defining functions. They utilize a "fat arrow" (=>) to represent the function body. However, it's worth noting that arrow functions sometimes use curly braces ({}), while others use parentheses(()).
Parentheses for Single-Line Return Expressions
When the arrow function's body consists of a single expression, parentheses are used to enclose the expression, indicating that the arrow function returns only that value. For instance:
const a = (who) => `hello ${who}!`;
This code defines an arrow function that returns a string. The parentheses around 'hello ${who}!' indicate that it's a single expression.
Curly Braces for Multi-Line Code Blocks
Curly braces are used when the arrow function's body contains multiple lines of code. Each line represents a statement, and the entire body becomes a code block. For example:
const handleBar = (e) => { e.preventDefault(); dispatch('logout'); };
This code defines an event handler that contains two statements, hence the need for curly braces.
Examples in Practice
Consider the following examples that illustrate the difference:
const b = (who) => ("hello " + who + "!"); const c = (who) => ( "hello " + who + "!" ); const d = (who) => ( "hello " + who + "!" );
Parentheses in Object Literals
Another use of parentheses in arrow functions is to enclose object literals. This is done to prevent the parser from treating the object as a code block.
const y = () => ({}); // returns an object
This code defines an arrow function that returns an empty object. The parentheses ensure that the parser interprets it as an object literal, not a code block.
Therefore, the use of curly braces or parentheses in arrow functions depends on whether the function body contains a single-line expression or multiple lines of code. Parentheses are used for single expressions, while curly braces are used for code blocks.
The above is the detailed content of Arrow Functions in JavaScript: When to Use Parentheses vs. Curly Braces?. For more information, please follow other related articles on the PHP Chinese website!