Death of the ‘for’ loop

“Universal Orlando roller coaster ride flipping upside down” by Claire Satera on Unsplash

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…

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.