💡TIP: Think of Array's reduce as a forEach, but with 1 added parameter, state. (a 🧵 thread)

Reduce encapsulates the state inside it's reducer, while the forEach leaves it's state in the scope.

#100daysofcode #javascript
The initial value is no longer set in the scope, like forEach. The initial value is passed in as the second argument into the reduce function. (a 🧵 thread)

#100daysofcode #javascript
The forEach sets the next value with state in the scope, while the reduce returns the next value. (a 🧵 thread)

#100daysofcode #javascript
The reducer has encapsulated the state and it can be extracted out of the reduce function. This allows the reducer to be re-used, moved to a different file or even another library.

This is something a reducer can do that a stateful forEach cannot.

(a 🧵 thread)
#100daysofcode
If you are still curious and want more, then I would recommend you click this link where I cover this comparison in my YouTube video on Array's reduce here:

(a 🧵 thread)

#javascript #100daysofcode
Here's some source code with a stateful forEach and a reducer for you to play with: https://runkit.com/joelnet/5f08ac8fdc7e4b001a3cbc27

#100daysofcode #javascript
You can follow @joelnet.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.