Well good!
Honestly the point of this article isn’t trying to say that using a loop is “wrong,” just that if you take the time to get comfortable with reduce
, you might see that it’s a lot more useful than you think. In the array total example, it’s hard to argue against reduce
, since it’s what it was designed for. That video (which really shows how terrible my timing is) also says that’s just fine. And the funny part is, I really agree with most of their examples, if you’re trying to return an array, use map
, if you’re filtering…use filter
. But the examples of object building, their “simplified” solutions actually seem less readable. Like this “bad” example using reduce here:
const events = Object.keys(this.state.events);
const handlers = events.reduce((events, event) => {
events[event] = this.eventDidFire.bind(this, event);
return events;
}, {});
Using reduce seems really straightforward compared to their solution below:
const handlers =
Object.fromEntries(Object.entries(this.state.events)
.map([key, value]) => ([
key,
this.eventDidFire.bind(this, key)
])));
Their version requires a a function with a callback chained to an iterator using array destucturing to handle the argument to create a tuple which is then transformed into a final object by the initial function, with 4 levels of indentation. Reduce is one callback with standard arguments in 2 lines using an object.
But ultimately, I think you’re right. I was trying to do an interesting use case, with a fancy one line solution to get people hyped, and I didn’t do a good job. Teaching stuff online through text is hard, and I’m really glad people nicely comment on stuff, because if it never “clicks” for the reader, I haven’t explained it well enough. I should put the real world explanation first, and then the fancy one as a bonus. I do hope I haven’t turned you off further from using reduce
. It’s not a super common iterator, but when it’s used right, it can really be a useful method.