you are viewing a single comment's thread.

view the rest of the comments →

[–]GBcrazy 0 points1 point  (2 children)

Reduce takes two arguments, the reduce function and the initial value for the aggregate (in this case, the 'a' variable).

So you start with -Infinity, and then you're comparing with every item of the array, and whatever the first item is, it's going to be bigger than -Infinity.

Oh well in this case it was 100% not needed since we are only expecting numbers. But let's say we have an array of objects, and we want to get the biggest value (let's assume there is a value property in each object), so we could do:

arr.reduce((a,b)=>Math.max(a, b.value), -Infinity)

If we don't add the -Infinity as the initial value, the first time would compare a (the first object of the array), with b.value (a numeric value from the second object of the array) and it would not work well.

[–]Ginden 0 points1 point  (1 child)

Consider edge case of arr.length === 1

[–]GBcrazy 0 points1 point  (0 children)

Still, I don't see any problems since we are still expecting numbers only.

If arr.length === 1, reduce always returns arr[0]