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