Death of the for loop

Rollercoaster going around a loop

Originally published on Medium - 3rd April 2018

So I was hit with a revelation recently. I haven’t written a for loop in months. Is this the end of it? Has it been replaced with functions like map, filter and find? Well, no, but definitely a reduced need.

Functional programming ideas are definitely leaking into everyday languages. First class functions definitely are a big part of this.

Take a React example. If I have a list of items, I’ll typically end up with code such as (written in TypeScript):-

<ul>
   {names.map((name: string) => <li key={name}>{name}</li>)}
</ul>

The alternative is:-

output(‘<ul>’);
for (let i = 0; i < names.length; i++) {
   output(`<li key=”${names[i]}”>${names[i]}</li>`);
}
output(‘</ul>’);

Something where I’d normally only show certain values, now use filter along with map.

<ul>
   {
      names
         .filter((name: string) => name.length > 2)
         .map((name: string) => <li key={name}>{name}</li>)
   }
</ul>

I know which I prefer…

Mastodon