Middle
What is the signature of the reduce method on arrays? What should be returned from the callback on each iteration?
sobes.tech AI
Answer from AI
The reduce method for arrays in JavaScript has the following signature:
arr.reduce(callback[, initialValue])
Where callback is a function with parameters:
function callback(accumulator, currentValue, currentIndex, array) {
// ...
return newAccumulator;
}
accumulatoris the accumulated value returned from the previous call to callback (orinitialValueon the first iteration).currentValueis the current element being processed.currentIndexis the index of the current element.arrayis the original array.
On each iteration, callback should return a new accumulator value, which will be passed to the next iteration. In the end, reduce returns the final accumulated value.
Example:
const sum = [1, 2, 3, 4].reduce((acc, val) => acc + val, 0);
console.log(sum); // 10