Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Clarify reduce()

...

If the default value is not supplied, reduce() returns the result of applying function to the first 2 items in the array, then applying the function to that result and the 3rd item, etc. If the array contains no items, 0 is returned. If the array has only one item, it the item is returned. 

If the default value is supplied, reduce() returns the result of applying function to the default value and the first item in the array, then applying the function to that result and the 2nd item, etc. If array contains no items, reduce() returns the default value and the function is not called. If the array has only one item, the item is returned.

Code Block
languagejavascript
themeConfluence
c = [4, 5, 6];
c.reduce(function(a,b){a + b})     // returns 15
c.reduce(function(a,b){a + b}, 10) // returns 25
c.reduce(function(a,b){a - b})     // returns -7; note left associativity


d = [];
d.reduce(function(a,b){a + b})     // returns 0
d.reduce(function(a,b){a + b}, 15) // returns 15 


m = [76];
m.reduce(function(a,b){a + b})     // returns 76
m.reduce(function(a,b){a + b}, 15) // returns 91

...