Curly Braces in Arrow Functions: A Puzzle Unveiled
In Dan Abramov's lectures, an intriguing question arises: why do curly brackets cause a function to fail its test? Let's investigate this enigma.
The code in question is an arrow function within a case statement:
case 'toggleTodo' : return ( state.map( (one) => { oneTodo( one, action ) }) );
When curly brackets { } are included, the tests fail. However, when they are omitted, the code works flawlessly. Here's what's happening under the hood.
The Power of the Brace: Blocks and Explicit Returns
When you enclose a function's body in curly brackets, you create a block. Blocks can contain multiple statements, each ending with a semicolon. If you want to return a value from a block, you must explicitly use a return statement.
In the case of the arrow function with curly brackets, the body consists solely of a call to oneTodo(). Since there is no explicit return statement, the function returns undefined. This unexpected behavior causes the test to fail.
To rectify this, you need to explicitly return the result of the oneTodo() call:
(one) => { return oneTodo(one, action); }
Concise Body: Omitting Braces for Simplicity
If you omit the curly brackets, the arrow function has a concise body. Concise bodies consist of a single expression, whose result is implicitly returned.
In the example without curly brackets, the concise body is:
(one) => oneTodo( one, action )
This expression is equivalent to:
return oneTodo( one, action );
By omitting the curly brackets, you achieve the same result without the need for an explicit return statement.
Understanding the Difference
The key takeaway is to understand the difference between a block (indicated by curly brackets) and a concise body (indicated by the absence of curly brackets). Blocks require explicit return statements, while concise bodies implicitly return the result of the single expression.
So, when using arrow functions in case statements, remember to use curly brackets and an explicit return statement if you need multiple statements in the function's body. If you only need a single expression, you can omit the curly brackets to create a concise body.
The above is the detailed content of Why Do Curly Braces Break My Arrow Function in a Case Statement?. For more information, please follow other related articles on the PHP Chinese website!