Open In App

What is Reduce in JavaScript ?

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:

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.




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
Article Tags :