JS loops & iterations

Article written by William Ribeiro

William Ribeiro HD

Iterations in JavaScript

Dealing with collections of things or doing a lot of repetition is part of the daily routine of a software developer. Be it a list of temperatures in a city, the rows in a book database, or painting every pixel on the screen, no matter what the need may be, the key concepts for us devs are: loops and iteration!

In JavaScript, there are 4 ways of looping that can be used for iterating over collections. Depending on which one you choose to perform the iteration, it might make the task at hand easier, harder, or maybe even impossible! So we must know well the details of each technique and choose wisely.

To help us compare the techniques, we'll try to implement a simple indexOf(arr, name) that takes an array of strings and a name to be found. It should return the index number of the name in the given array or -1 if not present.

Here's the array of names from one of my favorite cartoons when I was a kid: const characters = ['Leonardo', 'Donatello', 'Michelangelo', 'Raphael', 'Splinter'];

while

The first kind of loop I learned back in the day with the Pascal programming language and still today I find myself in infinite loops with it, yet it is as simple as:

 while( conditionIsTrue ) {

  // statements

} 


Here's how we could implement our function using it:

 function indexOfWhile(arr, name) {

  // 0-based index and also used for controlling the starting position and stop condition

  let index = arr.length - 1;

  // or maybe != -1 ... or was it > 0?

  while (index >= 0) {

    if (arr[index] === name) return index;

    index--; // looping backwards: end to start!

  }

  return index;

} 

As you can see it's very manual, therefore prone to errors. We are faced with many small decisions that are spread around many lines of code and are easy to miss and create bugs.

I prefer using while loops when the stop condition is simple and there aren't many repeated statements.

The classic for

Now, this is the kind of iteration loop I used by default for many years. The syntax rule is:


for ([initialization]; [condition]; [final-expression]) {

  // statements

 }


And here's the implementation of our function using it:

 function indexOfClassicFor(arr, name) {

  // 0-based index; define start position and stop condition

  // Concise but heavy.

  for (let i = 0; i < arr.length - 1; i++) {

    if (arr[i] === name) return i;

  }

  return -1;

} 

To me, even though the while and classic for loops look very different, they share the same weaknesses: dealing with many small code details is always a recipe for bugs.

do ... while

This one I almost never use. Not because it's useless, but because I'm not used to thinking about its main characteristic: it always runs the repeatable block at least once. The general syntax is

 do {

  // statements

}

while (conditionIsTrue);



Here's how it looks for our use case:

 function indexOfDoWhile(arr, name) {

    let index = 0;

    do {

      if (arr[index] === name) return index;

        index++;

      } 

      while (index <= arr.length - 1);

      return -1;

  } 

And once again this technique has the same weaknesses as the other two before.

My favorite but not perfect for ... of

What if we had a looping tool that took care of most of the decisions and made it safe and easy to do our jobs? That be great... oh well, the for ... of almost has it all. Its syntax:

 for (variable of iterable) {

  // statements

} 

And how it works for us:

 function indexOfForOf(arr, name) {

  let index = 0;

  for (const entry of arr) { // why u give me no index ?! =(

    if (entry === name) return index;

      index++;

    }

  return -1;

} 

It has almost everything:

  • We don't need to worry about where to start or to end

  • It will loop over every single element in the collection

  • It gives us a reference of the current iteration element automatically and we can make it immutable

  • It does not give us any indexes... which would be OK if that wasn't a requirement for our use case.

We can use Array.entries() for the rescue that will give us the pair [index, entry] and then the code is super duper cool!

 function indexOfForOfEntries(arr, name) {

  for (const [index, entry] of arr.entries()) {

    if (entry === name) return index;

  }

  return -1;

} 

Conclusion: master your tools

These 4 ways of looping all have their advantages and disadvantages. Only by mastering all of them, you'll be able to make sound decisions on which to use when.

In my day-to-day, I use for ... of very often as it's the most straightforward and safe tool for most loops and iterations.

Keep honing your skills and practice from time to time each.

CHALLENGE: 1ee7

Ok, now that we have covered some examples, let's have some real fun with a small challenge: Convert the names of the characters in the array to basic leetspeak. Use at least 2 different looping mechanisms.

The basic transformation rules of our simple leetspeak:


| Original letter | Converts to |
| --------------- | ----------- |
|        a        |       4     |
|        e        |       3     |
|        i        |       1     |
|        o        |   0 (zero)  |
|        t        |       7     |


Hard? I'm sure that now it becomes easier to loop with all such fancy tools!