The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

The reducer function takes four arguments:

Accumulator (acc)

Current Value (cur)

Current Index (idx)

Source Array (src)

Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

Syntax

Parameters

A function to execute on each element in the array (except for the first, if no initialValue is supplied), taking four arguments:

accumulator

The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).

currentValue

The current element being processed in the array.

indexOptional

The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.

arrayOptional

The array reduce() was called upon.

initialValueOptional

A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used and skipped. Calling reduce() on an empty array without an initialValue will throw a TypeError.

Return value

The single value that results from the reduction.

Description

The reduce() method executes the callback once for each assigned value present in the array, taking four arguments:

accumulator

currentValue

currentIndex

array

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

If the array is empty and no initialValue is provided, TypeError will be thrown. If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without callingcallback.

It is usually safer to provide an initialValue because there are three possible outputs without initialValue, as shown in the following example.