Rethinking JavaScript: Death of the For Loop
Joel Thoms
1.5K46

In general while in your example you made the code way “sexier” it is less performant quite a bit… Maybe that doesn’t matter in certain cases it might look more readable but this code has a big O(2N) which of course gets trimmed to O(N) so its no big deal, but still… The other is just O(N)period, and will finish the whole job in one loop.

Tim Roberts already noted break, which can optimize code speed a lot.

But there’s also the lack of return.

Let’s look at a more realistic but similar scenario:

Return in which box I can find Alice the kitten if you find her or just return a list of names of the other kittens (so I can pick my second favorite — but I really want Alice) — this is similar to an autocomplete search sorry we didn’t find Alice among kittens but we did find: ['Julie', 'Kristie', 'Mike'] the kittens.

A return would be perfect here:

let kittens = []
for (var i = 0; i < cats.length; i++) {
  if (isKitten(cats[i])) {
if (cats[i].name === 'Alice) {
return i;
}
kittens.push(cats[i].name)
}
}
return kittens;

Fancy tricks like

.map (will return what it will look like in the array),

.forEach (return is completely meaningless),

.filter (return will allow you to return whether this one is in or not)

You give up flexibility and speed for fanciness:

const aliceIndex = cats.findIndex(cat => isKitten(cat) && cat.name === 'Alice')
if(aliceIndex !== -1){
return aliceIndex
}
const kittens =
cats.filter(isKitten)
.map(getName)

And not to mention that the filter usage eliminates the possibility of getting the original indexes of the cats (so that this solution is great) if all you want is names… but if instead you wanted box numbers, you couldn’t use it at all unless you did something like..

const includeIndex = (cat, i) => {...cat, originalIndex: i}
const kittens = cats.map(includeIndex)
.filter(isKitten)
.map(cat => cat.originalIndex)

Which is now O(3N) again we can get rid of the constant but this is getting a bit crazy no?

One clap, two clap, three clap, forty?

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