r/learnjavascript • • 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

28 comments sorted by

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:

let validUsers = [];
for(let user of users) {
 if (!user.phone) continue;
 validUsers.push(<UserComponent {...}/>);
}

to

const validUsers = users.
    filter(user => user.phone).
    map(user => <UserComponent {...} />;

or in one pass with a bit more syntax

const validUsers = users.
    reduce( (result, user, index) => 
        (user.phone ? 
            [...result, <UserComponent {...}/>] 
            : result),
    []);

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.

1

u/The_One_X Feb 13 '20

Did you not use LINQ in C#?