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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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 withforEach
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 theArray.prototype
functions - but I'm definitely a lot closer than I was several years ago.