Introduction
Consider a simple scenario where you have an array of numbers and you want to return the sum of all elements in that array.
We will see that it's a solution in ES5 and that it's equivalent in ES6 to using reduce helper.
ES5 Code
- var numbers=[10,70,50,20];
- var sum=0;
- function additionOfElementsInArray(){
- for(var i=0;i<numbers.length;i++){
- sum += numbers[i]
- }
- return(sum);
- }
-
- additionOfElementsInArray();
The above code will return an output of 150.
ES6-Equivalent Code Using Reduce
- const numbers=[10,70,50,20];
-
- numbers.reduce(function(sum,numberElement){
-
- return sum += numberElement;
-
- } ,0 );
The above code will also return output as 150.
You can write the same code in ES6 using Reduce Helper with arrow function as follows, which will return the same output.
- const numbers=[10,70,50,20];
-
- numbers.reduce((sum,numberElement)=>sum += numberElement,0);
Description of Reduce method Syntax
arr.reduce(callback( accumulator, currentValue ), initialValue)
- The first argument of the Reduce method is the callback function which will return output. The second argument is the initial value of the first parameter (accumulator) of a callback function. In the above scenario, 0 is the initial value for the sum parameter.
- You can change the initial value. Eg. If I modify the above code for changing the initial value to 20, then the output will be 170 since the sum parameter will be initialized to 20.
- currentValue is the parameter for the current element value in the array.