The Syntax of Arrow Functions in JavaScript

Words
31
Reading
1 min
9y
Listen to this post
~1 min

The general form of arrow functions in JavaScript consists of the parameter list, the fat arrow, and the body block. Here is an example:

    let f = (a, b) => {
        let c = 4;
        return a + b - c;
    };

However, this could be simplified in some cases. First, if the parameter list contains only one parameter, the parentheses can be removed. For example,

    let f = x => {
        let y = 4;
        return x + y;
    };

Of course, if there are no parameters, the parentheses are required:

    let f = () => {
        let y = 4;
        return 2 + y;
    };

Second, if the body block consists only of a return statement, the curly braces and the return keyword can be eliminated. This is by far the simplest version:

    let f = x => x * x;

In this case, if the return value is an object literal, we need to put it in parentheses to avoid confusion with a block:

    let f = aname => ({
        name: aname
    });

Without parentheses, this could lead to confusing cases, because there are now many shortcuts for object literals. For example, the above function could also be written as the following:

    let f = name => ({
        name
    });

Without parentheses, this would be ambiguous.

The Syntax of Arrow Functions in JavaScript | Ecency