32

can someone, please explain the following:

I'm 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.

Yushin
  • 1,684
  • 3
  • 20
  • 36
Kayote
  • 14,579
  • 25
  • 85
  • 144
  • 2
    Looking at the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) should answer your question. – Felix Kling Feb 16 '16 at 18:37

3 Answers3

39

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:

(one) => {
    return oneTodo(one, action);
//  ^^^^^^
}

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
24
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

madox2
  • 49,493
  • 17
  • 99
  • 99
-2

It's a fair practice to use curly brackets when there are multiple statements inside an arrow function. Use curly braces to make multiple statements a single block and avoid getting errors inside an arrow function.

  • This adds almost nothing to the existing answers from 7 years ago. If you need to have multiple statements, t's not so much "fair practice" to use curly braces as much as "you have no choice if you want your code to be syntactically valid". – ggorlen Jan 11 '23 at 00:54
  • Sir here's the referral from javascript.info Multiline arrow functions : Sometimes we need a more complex function, with multiple expressions and statements. In that case, we can enclose them in curly braces. The major difference is that curly braces require a return within them to return a value (just like a regular function does) WEBSITE LINK: https://javascript.info/arrow-functions-basics this is what i actually meant to say. – YATENDRA UPADHYAY Jan 28 '23 at 16:50