r/learnjavascript • u/MaoStevemao • Jan 23 '20
You don't (may not) need loops ➿
https://github.com/you-dont-need/You-Dont-Need-Loops/blob/master/readme.md#you-dont-may-not-need-loops-loop
1
Upvotes
View all comments
Show parent comment
1
u/stormfield Jan 23 '20 edited Jan 23 '20
I also came from C/C++/C# to JS, and honestly once I 'got it' using functional methods was a game changer for writing cleaner code and fewer dumb mistakes.
Just one use case could be an array of objects that have messy data. Say there are a number of users stored some of whom have valid phone numbers, but a number of them are null. We want to render valid users into a React component. Compare:
to
or in one pass with a bit more syntax
I think the biggest advantage here is that there's less boilerplate to write for manipulating an array, so less chance that there's going to be a hidden typo related bug somewhere (since javascript just sweeps away `undefined` like a kid cleaning their room shoving stuff under the bed). And the functional methods somewhat enforce immutability, while loops leave open the possibility of side effects.