I've just come across an annoying bug (in my code) that was caused by the JavaScript Array.reduce method.
I've created a minimal reproduction of the issue below.
const people = [{name: 'bob'}, {name: 'fred'}, {name: 'john'}]
people.reduce((acc, person, i) => {
if (i === 0) throw Error('this error is never thrown')
if (i === 1) console.log(acc === people[0])
console.log(i, person.name)
return acc
})
people.reduce((acc, person, i) => {
if (i === 0) console.log(acc === null)
console.log(i, person.name)
return acc
}, null)
Why does the first piece of code above iterate twice only whilst the second use of reduce iterates three times (once for each array item) as expected?
Are there any docs documenting this behaviour or is this a bug in Chrome? If its not a bug, why does this behaviour exist? TIA
reduce() has the second param (optional) as initial value of the aggregation. From the docs:
If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.
In your code bob is skipped and so is its index. So this is the correct behaviour