Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
Sum is just about the only case where reduce is useful, but in reality it should never be passed around like that. Why keep an add function around that is only meant to be used together with a reduce? Just wrap it once and never use reduce again:
for loops either mutate data or perform side effects, which as a general rule why they are good to avoid.
map
,filter
, andreduce
also allow better code reuse and testability because it can be broken down further than a for loop can.Example:
You'll also notice all those
let
s go away and becomeconst
.Get rid of for loops and it's possible to write your entire program without a single
var
orlet
!I think you mean
You need a seed value.
Nope. That is exactly what I meant.
The seed is optional. If you don't provide a seed, the first item in the array is given as the accumulator.
Run the code!
Sum is just about the only case where reduce is useful, but in reality it should never be passed around like that. Why keep an
add
function around that is only meant to be used together with areduce
? Just wrap it once and never use reduce again:Don't tell me
arr.reduce(add)
makes more sense thansum(arr)
because it doesn't.In reality you can write
sum
event more efficiently with a regular loop and every part of your code benefits.But if you don't pass any initial value then there would be errors in case of empty arrays. Example: