Skip to content

Instantly share code, notes, and snippets.

@ansgarm
Created April 23, 2018 12:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ansgarm/41c781d7bdb523fc0fdcccce37029b3c to your computer and use it in GitHub Desktop.
Save ansgarm/41c781d7bdb523fc0fdcccce37029b3c to your computer and use it in GitHub Desktop.
PSA: Don't use es6 default parameters for Array.reduce() accumulator function
// PSA: Don't use es6 default parameters for Array.reduce() accumulator function
a = [1, 2, 3];
a.reduce((sum = 0, x) => sum + x); // = 6
a.reduce((sum, x) => sum + x, 0); // = 6
// seems to work...
c = a.reduce((sum = 3, x) => sum + x); // = 6
// but! other initial value doesn't have an effect
// even better
b = [{i: 1}, {i: 2}, {i: 3}];
b.reduce((sum, x) => x.i + sum, 0); // = 6
b.reduce((sum = 0, x) => sum + x.i); // = [object Object]23
// ffffuuuuuuu
// -> default parameters don't work as you'd expect with Array.reduce,
// because Array.reduce uses the first array element as accumulated
// value ("sum"), if you don't supply a second argument..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment