JS-Dev-101 practice question 2 of 25

A developer is required to write a function that calculates the sum of elements in an array but is getting undefined every time the code is executed. The developer needs to find what is missing in the code below. 01 const sumFunction = arr => { 02 return arr.reduce((result, current) => { 03 // 04 result += current; 05 // 06 }, 10); 07 }; Which line replacement makes the code work as expected?

Full set: 148 questions
Answer options
A: 03 if(arr.length == 0) { return 0; }
B: 04 result = result + current;
C: 02 arr.map((result, current) => {
D: 05 return result; Correct answer
Correct Answer:
D. 05 return result;
Explanation

Array.prototype.reduce’s callback must return the accumulator each iteration. Adding “return result;” (line 05) hands the updated value back to reduce, eliminating the undefined that occurs when nothing is returned.

Why Incorrect

A. Early-returning for an empty array has no effect on the missing return that causes undefined.
B. result = result + current still needs to be returned; omission keeps undefined.
C. map returns a new array, not a single sum; also fails to return inside reduce.

References

1. ECMA-262, 13th ed., §23.1.3.19 “Array.prototype.reduce”, steps 5–6 (accumulator is the value returned each callback).

2. Stanford CS193p “JavaScript ES6 Review” slides, p. 22 (reduce requires returning accumulator).

Scroll to Top