DEV Community

Discussion on: What s wrong with Array.reduce ?

 
costinmanda profile image
Costin Manda

I see what you are saying, but unless you are going to reduce that function, this can just as well be expressed by a forEach or a loop. One declaration of a variable above it doesn't bother me. Cheers!

Thread Thread
 
wulymammoth profile image
David

forEach just abstracts away the iterator variable boilerplate, but could still leave the collection variables scattered about, like at the top of the file and make it possible for someone to mutate them in between... but yah!

Thread Thread
 
icyjoseph profile image
Joseph

Pardon for jumping in but fold are very well studied functions, as you know :) Sorry for dropping a link, but it speaks much better than I could: Fold Higher Order Function

Thread Thread
 
tech6hutch profile image
Hutch

@wulymammoth your code is slightly wrong. You have to return the accumulator (the object of arrays, this case). You're instead returning whatever push returns (which is the length of the array after pushing). (Also, you're re-declaring the parameter num as a const, which isn't allowed, but that's a simpler fix.)

Thread Thread
 
wulymammoth profile image
David

All good catches