Explanation of Reduce Function in JavaScript.

Explanation of Reduce Function in JavaScript.

Understanding Reduce function in JavaScript

In Simple Words, it reduces the given array to a single value.

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

Syntax :

 yourArray.reduce(callback, initialValue)

Here ,

  • yourArray : the array to run the reducer function on.

  • Callback : Reducer Function

  • initialValue (optional ): it's the initial value of the accumulator, if it is not provided it is the default value of the array's first element.

Example without initialValue :

const Numbers = [2,3,1,4,5,6];
const reducer = (accumulator, currentValue) => {
        console.log(`Accumulator :  ${accumulator}`);
        console.log(`Current Array Element : ${currentValue}`);
        return accumulator + currentValue;
};

const sum = Numbers.reduce(reducer);
console.log(`Sum is ${sum}.`);

/*
 Accumulator : 2
Current Array Element : 3
Accumulator : 5;
Current Array Element : 1
Accumulator : 6
Current Array Element : 4
Accumulator : 10
Current Array Element : 5
Accumulator : 15
Current Array Element : 6;
Sum is 21.
*/

Example with initialValue :

const Numbers = [2,3,1,4,5,6];
const reducer = (accumulator, currentValue) => {
        console.log(`Accumulator :  ${accumulator}`);
        console.log(`Current Array Element : ${currentValue}`);
        return accumulator + currentValue;
};

const sum = Numbers.reduce(reducer,0);
console.log(`Sum is ${sum}.`);

/*
 Accumulator : 0
Current Array Element : 2
Accumulator : 2;
Current Array Element : 3
Accumulator : 5
Current Array Element : 1
Accumulator : 6
Current Array Element : 4
Accumulator : 10
Current Array Element : 5;
Accumulator : 15
Current Array Element : 6 
Sum is 21.
*/

Here is the basic and better examples to understand reduce() function easily.

Like and Share this Article, and also Follow for more JavaScript concepts.

Did you find this article valuable?

Support Javascript Blogs by becoming a sponsor. Any amount is appreciated!