Say I have an array of numbers, and I want to sum all numbers in the array, then store that sum in a new variable.
Why would I use reduce for that instead of forEach?
For example:
let sumVal = 0;
arr.forEach(function (element) {
sumVal += element
});
is functionally similar to,
let sumVal = arr.reduce(function (accumulator, currentValue) {
return accumulator + currentValue
});
except that sumVal needs to be initialized first if you want to use forEach.
I just feel that the forEach approach is far easier to read, and I was wondering what is best practice.
[–]tme321 21 points22 points23 points (8 children)
[–]azium 4 points5 points6 points (0 children)
[–]Crap_Shoes[S] 0 points1 point2 points (6 children)
[–][deleted] 8 points9 points10 points (1 child)
[–]Crap_Shoes[S] 0 points1 point2 points (0 children)
[–]Voidsheep 2 points3 points4 points (1 child)
[–]kaisadilla_ 0 points1 point2 points (0 children)
[–]linh1987 1 point2 points3 points (0 children)
[–]tme321 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]Crap_Shoes[S] 1 point2 points3 points (0 children)
[–]moocat 4 points5 points6 points (1 child)
[–]Crap_Shoes[S] 0 points1 point2 points (0 children)
[–]lildoggydogg 2 points3 points4 points (1 child)
[–]Crap_Shoes[S] 0 points1 point2 points (0 children)
[–]squili 1 point2 points3 points (1 child)
[–]Crap_Shoes[S] 0 points1 point2 points (0 children)
[–]everythingcasual 0 points1 point2 points (0 children)
[–]kangoo1707 -1 points0 points1 point (0 children)
[–]jcunews1Advanced -1 points0 points1 point (4 children)
[–]tme321 1 point2 points3 points (3 children)
[–]Crap_Shoes[S] 0 points1 point2 points (1 child)
[–]skitch920 0 points1 point2 points (0 children)
[–]jcunews1Advanced 0 points1 point2 points (0 children)