Home >Web Front-end >JS Tutorial >Arrow Functions and Curly Brackets: Implicit vs. Explicit Return?

Arrow Functions and Curly Brackets: Implicit vs. Explicit Return?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 12:14:12294browse

Arrow Functions and Curly Brackets: Implicit vs. Explicit Return?

Arrow Functions: The Curly Bracket Quandary

Dan Abramov's lectures and exercises provide a great learning experience. However, you may encounter a peculiar issue when using curly brackets in arrow functions. While the code works without these brackets, it fails when they are present.

The Reason:

The curly brackets create a block statement within the arrow function. This changes the behavior of the function, making it necessary to explicitly return a value using a return statement.

With Curly Brackets:

case 'toggleTodo' :
        return (
            state.map( (one) => {
                oneTodo( one, action )
            })
        );

In this example, the block statement requires a return statement for the function to return the oneTodo result.

Without Curly Brackets:

case 'toggleTodo' :
        return (
            state.map( (one) =>
                oneTodo( one, action )
            )
        );

When omitting curly brackets, the arrow function is considered to have a concise body. This means the oneTodo expression's result becomes the implicit return value.

To Resolve:

Ensure that when using curly brackets in arrow functions, you explicitly include a return statement to return the desired value.

The above is the detailed content of Arrow Functions and Curly Brackets: Implicit vs. Explicit Return?. 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