DEV Community

Discussion on: I Use For Loops Almost Always In Javascript

Collapse
 
ryansmith profile image
Ryan Smith • Edited

I usually opt for a loop due to simplicity and readability, not necessarily performance. I found the premature optimization comment that you received pretty shallow because of that. With something like .reduce(...), there is mental overhead to parse it and figure out what is going on. If it isn't calculating some type of sum or total, then it is being used only for the loop aspect. In that case, just use a loop!

It seems like many JavaScript devs look at a collection that they want to loop over and say "hmmm how can I use a SICK reduce on this". It is clever and shorter, but is it more readable? Most of the time, I would disagree.

JavaScript is a language that has some functional features incorporated into it, which is great. But I think taking that to the extreme and trying to make everything functional is not always the best approach. I'm not sure why the functional stance has become so prevalent in the JavaScript community.

Collapse
 
albertomontalesi profile image
AlbertoM

My ex colleague used to use fancyreduce all the time which made it so much harder for me as a Junior to understand what was going on. Fancy one-liners are cool on codewars or similar sites but not so much in actual code that everybody in the team needs to understand.

Collapse
 
beggars profile image
Dwayne Charrington

You hit the nail on the head here, Ryan. I have no idea where the functional mindset originated from. I know quite a few JS "thought leaders" are strong advocates for the functional approach and I honestly think React shares a lot of the blame for this in recent years.

Because of design choices and mistakes in React itself lending itself to things like hooks being created, their anti-classes/oop approach has resulted in an ecosystem of developers who don't question the approach and blindly assume that Facebook is the be-all and end-all of JS and follows them into the mouth of the volcano.

Just based on my experiences (and sounds like yours as well) I have seen what happens when "clever coders" think they are writing "clever code" and it always almost results in the code being rewritten eventually because it's trying to be too smart and nobody can work out what it is doing.

I have seen a lot of people advocating for using map as a means of looping over items in arrays where a for loop would be more appropriate. And in the case of reduce especially, I have seen some pretty crazy stuff.

And truth to be told, I have fallen into some traps with reduce before forgetting the first argument in the initial value or the previous value, because I am used to how methods like forEach return the value in the iteration first.

Collapse
 
budyk profile image
Budy

Agree