Open In App

How Reduce Work in JS

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The reduce() method in JavaScript is used to iterate over an array and accumulate a single result based on a callback function. It works by iterating through each element in the array and applying a function that takes the current element and the accumulated value (often called the "accumulator") and returns a new value for the accumulator.

array.reduce((accumulator, currentValue, currentIndex, array) => {
// return the updated accumulator
}, initialValue);

Parameter:

  • accumulator: The accumulated value that is returned after each iteration. It can be any type (number, array, object, etc.).
  • currentValue: The current element being processed in the array.
  • currentIndex (optional): The index of the current element being processed.
  • array (optional): The array that reduce() was called on.
  • initialValue (optional): The value to initialize the accumulator. If not provided, the first element of the array is used as the initial value, and the iteration starts from the second element.

How It Works Behind the Scenes:

  • Initial Value: If the initialValue is provided, the first iteration uses it as the accumulator. Otherwise, the first element of the array is used as the accumulator, and the iteration starts with the second element.
  • Callback Execution: For each element, the callback function is executed with the accumulator and current element. The callback returns the new accumulator value for the next iteration.
  • Final Result: After all iterations, the final accumulated value is returned.
JavaScript
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {\
 // Add the current value to the accumulator
    return accumulator + currentValue; 
}, 0);  // Initial value for the accumulator is 0

console.log(sum);  

Explanation:

  • First iteration: accumulator = 0, currentValue = 1 → new accumulator = 0 + 1 = 1
  • Second iteration: accumulator = 1, currentValue = 2 → new accumulator = 1 + 2 = 3
  • Third iteration: accumulator = 3, currentValue = 3 → new accumulator = 3 + 3 = 6
  • And so on until the final sum is 15.

Next Article
Article Tags :

Similar Reads