Refer to the code below:
01 const myFunction = arr => {
02 return arr.reduce((result, current) => {
03 return result + current;
04 }, 10);
05 }
What is the output of this function when called with an empty array?
We call:
myFunction([]);
Inside:
arr.reduce((result, current) => {
return result + current;
}, 10);
Key points about Array.prototype.reduce:
Signature: array.reduce(callback, initialValue)
If initialValue is provided and the array is empty, reduce:
Does not call the callback at all.
Simply returns initialValue.
Here:
arr is [] (empty).
initialValue is 10.
So:
No iterations of the callback happen (no elements to process).
The return value is the initial value: 10.
So the actual output is:
myFunction([]) === 10;
Among the options:
A: 0 -- incorrect, because the initial value is 10, not 0.
B: Throws an error -- reduce throws only if the array is empty and there is no initialValue. Here we have an initial value, so no error.
C: NaN -- there is no arithmetic with undefined or invalid values; we just return 10.
D: Returns 5 -- the numeric value given is wrong; the correct value is 10.
Given the logic, the correct conceptual result is 10. The option text ''Returns 5'' is almost certainly a typo for ''Returns 10''. Since the letter that is intended to represent the correct behavior is D, we keep:
Answe r: D
Study Guide / Concept Reference (no links):
Array.prototype.reduce behavior with initialValue
Behavior of reduce on an empty array with and without initialValue
Return value when no iterations run
Currently there are no comments in this discussion, be the first to comment!