Kayote
Kayote

Reputation: 15617

Curly Brackets in Arrow Functions

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.

Upvotes: 33

Views: 9703

Answers (4)

Hakan
Hakan

Reputation: 589

foo = function() {
  return "bar!";
}


foo = () => {
  return "bar!";
}

foo = () => "bar!"; 

Upvotes: -1

YATENDRA UPADHYAY
YATENDRA UPADHYAY

Reputation: 1

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.

Upvotes: -2

Bergi
Bergi

Reputation: 664124

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.

Upvotes: 41

madox2
madox2

Reputation: 51841

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

Upvotes: 26

Related Questions