Search code examples
javascriptnode.jslambdaecmascript-6arrow-functions

Using curly braces in an array reduce function?


If fn3 is substituted for fn2 in this example running in node 9.5.0 the console.log(totalUpvotes) will log undefined. IIUC the result should be the same (92)?

    const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: 3, upVotes: 1}];

    const fn2 = (totalUpvotes, currentPost) => totalUpvotes + currentPost.upVotes;

    const fn3 = (totalUpvotes, currentPost) => {totalUpvotes + currentPost.upVotes}

    const totalUpvotes = posts.reduce(fn2, 0);

    console.log(totalUpvotes);

Solution

  • When the runtime sees that the curly braces are omitted, it includes the return statement for you. See example below, as well as Arrow functions on MDN:

    (param1, param2, …, paramN) => { statements } 
    (param1, param2, …, paramN) => expression
    // equivalent to: => { return expression; } 
    

    Note the equivalency of the form that takes an expression with the form that takes statements. The form that takes statements will always result in an undefined return value unless terminating with an appropriate return.

    JavaScript does not have an "implicit statement block value"; with the exclusion of object-literals, {} braces always introduce some form of a non-expression.

    See this example:

    es6 console

    Here it is for the impatient:

        "use strict";
    
        var fn2 = function fn2(totalUpvotes, currentPost) {
          return totalUpvotes + currentPost.upVotes;
        };
    
        var fn3 = function fn3(totalUpvotes, currentPost) {
          totalUpvotes + currentPost.upVotes;
        };