The Wayback Machine - https://web.archive.org/web/20250226125046/https://www.geeksforgeeks.org/what-is-reduce-in-javascript/
Open In App

What is Reduce in JavaScript ?

Last Updated : 01 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Syntax:

array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);

Parameters:

  • callback: A function that is called once for each element in the array.
    • accumulator: The accumulated result of the previous callback invocation or initialValue if provided.
    • 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.
  • initialValue: (Optional) A value to use as the initial accumulator. If not provided, the first element of the array is used as the initial accumulator.

Example: Here, the reduce() method is used to add up all the elements of the numbers array. The callback function takes two parameters (accumulator and currentValue) and returns the sum of these values.

JavaScript
let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

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

Output
15

Next Article

Similar Reads

three90RightbarBannerImg