The reason it’s needed is that sometimes, you’ll be receiving arrays of length 0 or 1. In these cases, special, and perhaps unexpected, things happen.
Empty array
Let’s say you have an empty array.
[].reduce((a, b) => a + b)
It does not know what to do. It doesn’t know what to set a
and b
to. It throws an error – and that’s not good.
[].reduce((a, b) => a + b, 19)
This code, however, will result in no error – and will return 19, the default value.
Array of length 1
Now, let’s take a look at another example.
[4].reduce((a, b) => 10)
What does that output? Well, because the array only contains one element, and there’s no default value, reduce
will just return that element. So the return value is 4, not 10. This seems silly. Had any more values in the array, we would’ve reduced to 10
– it’s just a weird result.
So, let’s add a default value.
[4].reduce((a, b) => 10, "lol")
This results in 10. Why? Because JavaScript could now determine the value of both a
and b
. a
was set to 4, and b
was set to "lol"
. Hence, the function was called and its return value (10) was used.
Why it worked in your case
So what happened?
Not providing an initial value is legal – it’s an optional value after all. And if you do this, initialValue
becomes the first element in the array (and the first element is skipped, so you don’t get two identical arguments).
As demonstrated above, this is totally cool… until your array has no elements, and an error is thrown; or one element – where in this case it wouldn’t matter (the sum of a single element is the element itself). But in other cases it would, and therefore it’s a good practice to stick to.
But also, note that had you done this:
return args.reduce((a, b) => a + b, undefined);
Then your function would output NaN
(except when there’s no elements, then it’s undefined
). Why? Because undefined + 5
(or any number for that matter) is NaN
.
Hence, if you’re going to set it, you must ensure you’re setting it to the correct value. And you definitely should, people will pass empty arrays, because people are annoying.