.reduce
is one of the more powerful array methods, but how it works isn’t extremely clear, and understanding how it works requires some time studying it.
Ultimately .reduce
functions as a method that allows you to “reduce the array down to a single variable” you build up over each iteration. This might sound wordy, but here is an example of some code where you “reduce an array down to a single variable”
const getSum = (nums) => {
let sum = 0;
for (let num of nums) sum += num;
return sum;
};
console.log(getSum([1, 2, 3])); // 6
This code iterates over the array of numbers, nums
, and adds it to the sum
.
So essentially you are “reducing” the nums
down to sum
, with a starting value of 0
.
If you wanted to create the same function using .reduce
you’d do the following:
const getSum = (nums) => {
return nums.reduce((sum, num) => {
return sum += num;
}, 0);
};
console.log(getSum([1,2,3]); //6
or if we wanted to be a concise as possible, leveraging how arrow functions work without {}
, we can get:
const getSum = (nums) => nums.reduce((sum, num) => sum += num, 0);
console.log(getSum([1,2,3]); //6
In essence, the callback function passed can be used to “update” the “accumulator value” (in the examples sum
, or the first argument passed into the callback) with whatever the second argument is (num
). Whatever you return from the callback is then used as the next call’s sum
value.
So over each call, the function can be used to “reduce” the value of the array down to just that 1 value your passing through (sum
).
You originally asked about why 0
is there, that is just the default value. As mentioned above, if this isn’t passed, reduce
will automatically take the first value from the array. So in the last example, the first call of the callback, will have sum
set as 0
. If we didn’t pass 0
, the first call of the callback will have sum
set as 1
, as that is the first value in the array!
The callback for reduce
has other arguments that are less used, most of the time you’d use just the first 2 arguments. More information can be found in the official docs linked above on MDN.
In summary reduce
is powerful, but requires some playing around with to fully understand.
reduce
could be used in more complex cases, beyond just adding numbers, and fit essentially any scenario where you have a loop and a “value” that will be updated/set according to every value within an array.