Home > Web Front-end > JS Tutorial > Implicit vs. Explicit Returns in Arrow Functions: When Are Curly Brackets Necessary?

Implicit vs. Explicit Returns in Arrow Functions: When Are Curly Brackets Necessary?

Barbara Streisand
Release: 2024-12-14 11:55:10
Original
712 people have browsed it

Implicit vs. Explicit Returns in Arrow Functions: When Are Curly Brackets Necessary?

Curly Brackets in Arrow Functions: Implied vs Explicit Returns

Arrow functions can be written in two ways: with or without curly brackets. When curly brackets are absent, the function's body is considered a "concise body" and the last expression within it is implicitly returned.

Implied Return with Concise Body

In the example without curly brackets:

state.map(one => oneTodo(one, action))
Copy after login

The function immediately returns the result of calling oneTodo on the one argument.

Explicit Return with Block

When curly brackets are introduced, as in the first code block:

state.map(one => {
  oneTodo(one, action)
})
Copy after login

A block is created, and it must explicitly return a value. The return statement in this block is necessary to indicate what value should be returned.

When to Use Curly Brackets

  • Multiple statements: If the function body contains multiple statements, curly brackets are required to group them.
  • Explicit return: When you need to explicitly specify a return value, use curly brackets and a return statement.

In the context of the example provided, the code works both ways because the concise body implicitly returns the result of oneTodo. However, the tests fail when curly brackets are used without an explicit return because there is no value to return. Therefore, for clarity and consistency, it's recommended to use curly brackets and an explicit return statement when the function body contains multiple statements or requires explicit return values.

The above is the detailed content of Implicit vs. Explicit Returns in Arrow Functions: When Are Curly Brackets Necessary?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template