Array.prototype.reduce() || reduce() || ✂️
reduce()method executes a reducer function (that you provide) on each member of the array resulting in a single output value→MDN
const arr = [3, 4, 2, 9];
const reduce=(accumulator, currentValue)=>accumulator+currentValue;
In the above code, we create a reduce function which will be passed as a callback to the
.reduce() function. The function returns the addition of all the elements in the array. The
accumulator stores the sum of the elements after every iteration and
currentValue represents the value currently processed. The default value of the accumulator is 0 and can also be user defined as done in the second
console.log as 7. The accumulator is returned as a final result.
with for loop
const arr = [3, 4, 2, 9];
From 3 lines we go to 7 lines.
reduce calls a provided
callback function upon each element in the array and is called only for indexes for which the array contains a value.
callback is given 4 arguments
The first time when the
callback is called just before processing the first value the
currentValue will be the first element in the array while the
accumulator will have the value of the first element of the array or the value which is specified by the user in the
If the accumulator is provided a value then
reduce will start the
callback from index 1 and skip the first index as
accumulator already has the value of the first index. If initially the value is provided the
callback will start from the first index.
The first time the callback is called,
currentValue can be one of two values. If
initialValue is provided in the call to
accumulator will be equal to
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.
If the array is empty and no initial value is given to the
TypeError is thrown.
It is usually safer to provide an initial value because there are three possible outputs without
initialValue, as shown in the following example.
Let’s dissect it-
Parameters– The parameters taken by the
reduce function is a callback function which in turn takes parameters accumulator, index, array & currentValue.
- currentValue→ It is the current element which is processed by the
- array|optional→The array on which the
reducewas called upon.
- index|optional→ The index of the current element which is being processed in the array.
- accumulator|optional→ Value to use as the first argument on the first call of the
reduce returns the value left after reduce is done(