Sobes.tech
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;
}
  • accumulator is the accumulated value returned from the previous call to callback (or initialValue on the first iteration).
  • currentValue is the current element being processed.
  • currentIndex is the index of the current element.
  • array is 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
What is the signature of the reduce method on arrays… - sobes.tech