How does reduce() work?

QuestionsQuestions8 SkillsProNumPy Universal FunctionsOct, 02 2025
089

The reduce() method in JavaScript is used to execute a reducer function on each element of an array, resulting in a single output value. It takes two parameters: a callback function and an optional initial value.

Syntax

array.reduce((accumulator, currentValue, currentIndex, array) => {
    // logic to combine values
}, initialValue);

Parameters

  • accumulator: The accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
  • currentValue: The current element being processed in the array.
  • currentIndex (optional): The index of the current element being processed.
  • array (optional): The array reduce() was called upon.

Example

Here's a simple example that sums all the numbers in an array:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0); // Initial value is 0

console.log(sum); // Output: 15

In this example:

  • The reduce() method iterates over each number in the numbers array.
  • The accumulator starts at 0 (the initial value) and adds each currentValue to it.
  • The final result is the sum of all numbers in the array.

0 Comments

no data
Be the first to share your comment!