Search code examples
javascriptarrow-functions

What is the correct arrow function syntax?


Arrow functions can be written in a lot of different ways, are there any way that is "more correct"?

let fun1 = (a) => { return a; }
let fun2 = a => a;

Just like those cases above, is fun2 faster then fun1? What's the diference between them?


Solution

  • Arrow functions can be written in some diferent ways, like below:

    // No params, just returns a string
    const noParamsOnlyRet = () => 'lul';
    
    // No params, no return
    const noParamsNoRet = () => { console.log('lul'); };
    
    // One param, it retuns what recives
    const oneParamOnlyRet = a => a;
    
    // Makes the same thing that the one above
    const oneParamOnlyRet2 = a => { return a; };
    
    // Makes the same thing that the one above
    const oneParamOnlyRet3 = (a) => a; 
    
    /* Makes the same thing that the one above, parentheses in return are optional,
     * only needed if the return have more then one line, highly recomended put 
     * objects into parentheses.
    */
    const oneParamOnlyRet4 = (a) => (a);  
    
    // Mult params, it returns the sum
    const multParamsOnlyRet = (a, b) => a + b; 
    
    // Makes the same thing that the one above
    const multParamsOnlyRet2 = (a, b) => { return a + b; }
    
    // Curly brackets are needed in multiple line arrow functions
    const multParamsMultLines = (a, b) => { 
        let c = a + b;
        return c;
    }
    

    So we have some rules:

    • Parentheses around the params are needed when the function has none or more than one param, if it have just one, parentheses can be omitted.
    • If the function just have a return the curly brackets and the keyword return can be omitted, if it fits in one line
    • Curly brackets are needed if the function have more than one line or if it have no return.

    As you can see, all of this are valid syntax for arrow functions, none of them is faster than the other, which one you use depends of the way that you code.