0

When reduce is performed on an empty array with an empty array set as its initial value, apparently a value can't be pushed to that initial empty array (pushing isn't possible), whereas it can when reduce is performed on an array with a null value. Why doesn't it work in the first scenario without the null value?

Why doesn't [] set as the initial value (the second parameter of reduce) count as an element? For example, you can perform reduce on an empty array with 0 set as the initial value: [].reduce((prev, curr) => prev + curr, 0) // 0

[].reduce((arr, curr) => {
    arr.push('val')
    return arr
}, []);
// []
[null].reduce((arr, curr) => {
    arr.push('val')
    return arr
}, []);
// ['val']

3 Answers 3

1

An empty array have no element, so it dose not run reduce function. But [null] array has one element 'null'. So this array run reduce function.

Sign up to request clarification or add additional context in comments.

1 Comment

Please see updated question. Why doesn't [] set as the initial value (the second parameter of reduce) count as an element?
0

The first reduce is working as intended. As it is already reduced it will not perform anything.

To be more explicit, the callback you pass to the reduce() method will be called on each element of the array, but as your array is empty, there it will not be called.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce.

2 Comments

Please see updated question. Why doesn't [] set as the initial value (the second parameter of reduce) count as an element?
You set [] as initial value of the accumulator, and then for each element of the empty array (so, none) it will apply the reduction function, in total 0 amount of times. In that case your result is equal to the initial value.
0

As mentioned in the docs:

The reduce() method executes a user-supplied “reducer” callback function on each element of the array

If there are no elements the callback won't run

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

1 Comment

Please see updated question. Why doesn't [] set as the initial value (the second parameter of reduce) count as an element?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.