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. }  
  9.    
  10. additionOfElementsInArray();  

The above code will return an output of 150.

ES6-Equivalent Code Using Reduce

  1. const numbers=[10,70,50,20];   
  2.    
  3. numbers.reduce(function(sum,numberElement){  
  4.    
  5.    return sum += numberElement;  
  6.    
  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];  
  2.    
  3. numbers.reduce((sum,numberElement)=>sum += numberElement,0);

#es6 #es5 code #es6-equivalent code

ES6 Reduce Helper and ES6-Equivalent Code Using Reduce
2.90 GEEK