ES6 Reduce Helper


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
  1. var numbers=[10,70,50,20];   
  2. var sum=0;  
  3. function additionOfElementsInArray(){  
  4.    for(var i=0;i<numbers.length;i++){  
  5.          sum += numbers[i]  
  6.    }  
  7.    return(sum);  
  8. }  
  10. additionOfElementsInArray();  
The above code will return an output of 150.
ES6-Equivalent Code Using Reduce
  1. const numbers=[10,70,50,20];   
  3. numbers.reduce(function(sum,numberElement){  
  5.    return sum += numberElement;  
  7. } ,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.
  1. const numbers=[10,70,50,20];  
  3. 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.