"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Implicit vs. Explicit Returns in Arrow Functions: When Are Curly Brackets Necessary?

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

Published on 2024-12-24
Browse:188

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))

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)
})

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3