Reduce allows us calculate a total, applying an operation on every operation of an array.
This can save us lot of "for" loops (enhannce readibility).
Let's implement a function that will sum up an array.
Usually we would do something like:
const sales = [20, 30 ,25];
function totalSales(sales) {
let totalSales = 0;
for(let i=0;i< sales.length;i++) {
totalSales += sales[i];
}
return totalSales;
}
console.log(totalSales(sales));
By Using reduce:
const sales = [20, 30 ,25];
function totalSales(sales) {
return sales.reduce((total, sale) => total += sale)
}
console.log(totalSales(sales));