0

I came across the following JavaScript in Kyle Simpson's @kyle-simpson book Functional-Light JavaScript and am curious about part of its syntax:

    const double = v => v * 2;

    const reducer = (list, v) => (list.push(double(v)), list);

    var doubled = [1, 2, 3, 4, 5].reduce(reducer, []);

    console.log(doubled);
    //[2, 4, 6, 8, 10]

    var reduced = reducer([3], 2);

    console.log(reduced);
    //[3, 6]

Specifically I am not certain about the meaning and usage of the outer parentheses surrounding the reducer function's return value:

(list.push(double(v)), list)

Wrapping a object literal in parentheses is a way to implicitly return it from an arrow function but this appears to be something different.

Also:

var val = (3, 2);

console.log(val);
//2

This seems to suggest the parentheses will return the last value in its list, which would match the signature of the reducer function, but I do not know what this construct is called.

Thanks in advance for your reply.

Jason Bowers
  • 476
  • 6
  • 11
  • 5
    This is known as comma operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Thiago Barcala Apr 25 '18 at 15:17
  • 1
    *Hints*: `(3, 4)` evaluates to 4. So does `(console.log('side-effect'), 4)`. – Jared Smith Apr 25 '18 at 15:21
  • 1
    I love to use comma in `reduce` for side-effects on stackoverflow comments, because it makes very short code. However, i don't know if it's a good idea in production code, possibly less readable than writing out a code block. – ASDFGerte Apr 25 '18 at 15:22

0 Answers0