DEV Community

Discussion on: Applying To Facebook

Collapse
 
miketalbot profile image
Mike Talbot ⭐

I'd love to hear how you are improving your reduce and map. I do use them, not sure I feel I really like how I use them...

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Same here. I now use Array.prototype functions frequently. But too often, I first start out with .forEach() and then, once I've written the dang thing, I look back at it and think, "Oh... wait. This should really be done with map/filter/reduce/whatever." Then I spend a few minutes refactoring it.

Thread Thread
 
loujaybee profile image
Lou (🚀 Open Up The Cloud ☁️)

Very rarely, if ever does something need to be a .forEach as opposed to a reduce/map etc. That said, as much as I do love functional (and functional-esque) programming, other languages do advocate for just using humble for-loop, and I see their point, it's not evil.

Thread Thread
 
bytebodger profile image
Adam Nathaniel Davis

Oh, I totally agree! The thing is that my old-skool brain just kinda "fits" naturally into loops. So when I'm first thinking through the solution, I often reach for the forEach as the first thing out of the toolbox.

You're absolutely correct that a for loop is not "evil". But I've also learned that, as you pointed out, something rarely needs to be a forEach. And when I fall into a lazy habit of submitting code that's littered with forEach loops, the other devs on my team tend to notice (rightfully so).

So rather than beat myself up over it, I just write the logic the way it first "appears" in my brain. Then I give it a once-over, and I might refactor some of those forEach loops if they don't feel optimal. (And as you said, they rarely are.)

I used to be this way about ternary operators. I would write everything with traditional if/else, then I would look at it and think, "This should be a ternary" - so I'd change it. It took quite a while, but now I pretty much "think" in ternaries. I'm not quite there yet with all of the Array.prototype functions - but I'm definitely a lot closer than I was several years ago.