Basic Reduce Function Example in JavaScript

Modern versions of JavaScript include helpful functions that can help automate processes, especially processes related to enumeration. Here is an example of how to implement JavaScript's reduce() function to total an array of numbers:

const nums = [1, 5, 10, 2, 21];
const sum = nums.reduce((total, i) => total += i);
console.log(sum);

 

Notice that the reduce function takes a function as an argument, and that function (which the example uses the arrow based function syntax for) takes in a total and an accumulator as arguments. 

The reduce function can also take additional arguments if you need more granular access to the process, this table shows the breakdown for this example code:

[0, 1, 2, 3, 4].reduce(
  function (
    accumulator,
    currentValue,
    currentIndex,
    array
  ) {
    return accumulator + currentValue;
  }
);

 

callback accumulator currentValue currentIndex array return value first call 0 1 1 [0, 1, 2, 3, 4] 1 second call 1 2 2 [0, 1, 2, 3, 4] 3 third call 3 3 3 [0, 1, 2, 3, 4] 6 fourth call 6 4 4 [0, 1, 2, 3, 4] 10