Created
April 23, 2018 12:27
-
-
Save ansgarm/41c781d7bdb523fc0fdcccce37029b3c to your computer and use it in GitHub Desktop.
PSA: Don't use es6 default parameters for Array.reduce() accumulator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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