reduce & reduceRight function in JavaScript

Share the post

Hello All, In the last JavaScript tutorial we had discussed What is hoisting in JavaScript.Now, In this topic We will discuss What is reduce() & reduceRight() function in JavaScript? We discuss this concept with the help of an example.

What is reduce() function in JavaScript?

reduce() function is used to return a single output from the array. The main use of reduce() is it will not change our original array.
Execution is done from left to right.

We are passing four arguments in reduce() function as shown below:

array.reduce(accumulatorVal , currValue, currIndex, array)

In the above syntax, we have the first argument as accumulatorVal which holds the total value, In the second argument, We are passing currValue. Both values are compulsory arguments for reduce() function. Whereas, currIndex & array are optional arguments.

Example

In this example, We are simply doing the addition of all array elements. Please see below example

JAVASCRIPT

let tempArr = [1, 5, 10, 40, 78];
let newArr = tempArr.reduce((preVal, curVal) => {
    return preVal + curVal;
})

console.log(newArr);
document.getElementById('resultData1').innerHTML = newArr;

HTML

<h4>Result is reduce() function</h4>
<p id="resultData1"></p>

In the above example, We are using one tempArr array which contains some numbers. Suppose, we want to add all the array elements & return the value, We must go with reduce() function. If you see the output it will give 134.

NOTE : The only difference between reduce() & reduceRight() is execution done in reduceRight() is from right to left.

What is reduceRight() function in JavaScript?

reduceRight() function is used to return a single output from the array. The main use of reduceRight() is it will not change our original array.
Execution is done from right to left.

Example

In this example, We are simply doing the subtraction of all array elements. Please see below example

JAVASCRIPT

let tempArr1 = [1, 5, 10, 40, 78];
let newArr1 = tempArr1.reduceRight((preVal, curVal) => {
    return preVal - curVal;
})

console.log(newArr1);
document.getElementById('resultData2').innerHTML = newArr1;

HTML

<h4>Result is reduceRight() function</h4>
<p id="resultData2"></p>

For the above example, We will get the subtraction of all elements in the array. In this case, It’s 22.

Output for both above examples is as shown below

reduce_reduceRight_output
reduce & reduceRight output

1 thought on “reduce & reduceRight function in JavaScript”

Leave a Comment