Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 519
Kayote Avatar asked Feb 16 '16 18:02

Kayote


People also ask

What do curly brackets mean in functions?

Braces or curly brackets { } are used when the domain or range consists of discrete numbers and not an interval of values. If the domain or range of a function is all numbers, the notation includes negative and positive infinity .

What does {} in Python mean?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

Do arrow functions need curly braces?

Without curly braces, you can only put one expression to the right of the arrow => . Intuitively, this means you can only use the no curly brace syntax for "one-liners". You can use the ternary operator ? , && , and || . But you cannot use if statements or semicolons.

How are arrow functions () => {} different than traditional function expressions?

In regular function, arguments will give you list of parameter passed in function, In arrow function arguments is not defined. In regular function, you always have to return any value, but in Arrow function you can skip return keyword and write in single line. In arrow function parameters should be unique.


2 Answers

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.

like image 90
Bergi Avatar answered Oct 27 '22 10:10

Bergi


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

like image 39
madox2 Avatar answered Oct 27 '22 10:10

madox2