Curly Brackets in Arrow Functions

2019-01-05 05:38发布

Would someone please explain the following:

Im following Dan Abramov's lectures & doing the exercises.

The code works fine, however the tests fail when the following particular function is written with curly brackets **{ }**.

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

The same code works fine without curly brackets.

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

Here is the JsBin. Please refer to line 31 onwards.

2条回答
一纸荒年 Trace。
2楼-- · 2019-01-05 06:30
case 'toggleTodo' :
    return (
        state.map( (one) => 
            oneTodo( one, action )
        )
    );

is equal to:

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

see the return statement

查看更多
虎瘦雄心在
3楼-- · 2019-01-05 06:34

The pair of braces forms a block, containing a list of statements. You need to use a return statement explicitly to make the function return something.

If you omit the braces, the arrow function has a concise body, which consists solely of a single expression whose result will implicitly become the return value of the function.

查看更多
登录 后发表回答