JavaScript Array reduce() Method

JavaScript Array reduce() Method reduces the given array into a single value by executing a reducer function.

The reduce() method executes a reducer function for array element.

The user implements the reducer function that works on every element present in the array.

In this tutorial, you will learn about the JavaScript Array reduce() method with the help of examples.

The reduce() method returns a single value: the function’s accumulated result.

The reduce() method does not execute the function for empty array elements.

The reduce() method does not change the original array.

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • function(): Required. A function to be run for each element in the array.
  • total/accumulator: Required. The initialValue, or the previously returned value of the function. It accumulates the return values of the callback function, returned in the last calling of the function.
  • currentValue: Required. The value of the current element.
  • currentIndex: Optional. The index of the current element.
  • arr: Optional. The array the current element belongs to.
  • initialValue: Optional. A value to be passed to the function as the initial value.

If we do not provide the initial value, the callback function will start its execution with index as 1, where it will skip the first index. Although, if intialValue is provided, execution will begin from 0.

In case of an empty array with no initialValue is supplied, it will throw a TypeError.

reduce() executes the given function for each value from left to right.

If the array is empty, but initialValue is provided, or if the array contains one element, but no initialValue is supplied, that element will return without invoking the callback function.

Return Value

The accumulated result from the last call of the callback function.

Examples

const message = ["JavaScript ", "is ", "fun."];

// function to join each string elements
function joinStrings(accumulator, currentValue) {
  return accumulator + currentValue;
}

// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);

// Output: JavaScript is fun.
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10
const getMax = (a, b) => Math.max(a, b);

// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100
[    50].reduce(getMax, 10); // 50

// callback is invoked once for element at index 1
[1, 100].reduce(getMax);     // 100

// callback is not invoked
[    50].reduce(getMax);     // 50
[      ].reduce(getMax, 1);  // 1

[      ].reduce(getMax);     // TypeError