You can use reduce anywhere you could use a for or forEach loop. The main thing to understand about it is that what you return within it will be held onto for the next iteration, until you get through the entire collection you're reducing. You can actually implement map, filter, and forEach as variations of reduce, if you want to!
You can use
reduce
anywhere you could use afor
orforEach
loop. The main thing to understand about it is that what youreturn
within it will be held onto for the next iteration, until you get through the entire collection you're reducing. You can actually implementmap
,filter
, andforEach
as variations ofreduce
, if you want to!The most common example of a reduce is to sum a bunch of numbers, but you can also use it to join things as strings …
Or you can use it to do a simple (naïve) reverse!
The essential thing to remember:
reduce
is basicallyfor
, only more FP about it.