Which JavaScript for loop should I use?

When given a choice of 4 seemingly different ways to do the same thing, I've always been the person that wants to know what the difference is? To often we can blindly write code the way the person before us did and not understand the reason to do it a certain way, but what if the scenario has changed. When multiple options exist there's usually a reason why. It can be a language style improvement to make things easier to write, but more often than not there's a fundamental difference in what it actually does.

So, for loops, four seems like a lot, gotta be some differences right?

for

This is likely to be the first type of for loop you encounter when learning to program. It's a very manual type of loop where you create a initial expression, a condition expression to keep running the loop and an increment expression.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

// Result:
// 0
// 1
// 2
// 3
// 4

The big downside of the for loop is it doesn't actually loop through a collection. e.g. If you had an array and wanted to loop through each of it's objects you could do this as follows:

const arr = ['a', 'b', 'c'];

for (let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
}

In effect the loop is incrementing a number and you then use that number to access the position of the array. The result is you have more code to write that isn't serving any real purpose.

However as this is a much more manual loop process you have far more control over the loop. e.g.

  • You could increment by a different number.
  • You could go backwards.
  • The condition might not be linked to the length of an array.
  • You might not even be looping through an array.

Pros

  • Potentially faster in performance.
  • Break statement can be used to come out of the loop.
  • It works with the await keyword.
  • Not just for looping through arrays.

Cons

  • Not as readable as others.
  • You have more code to write.

for...in

You probably don't want this one. Here's an example:

const arr = ['a', 'b', 'c'];

for (const i in arr) {
  console.log(arr[i]);
}

// Result:
// "a"
// "b"
// "c"

Although we're now specifically looping through a collection like an array and don't need to do all of that i < array.length stuff, what we're given isn't the object in the array but a property name to access it on the object.

Here's another example:

const arr = ['a', 'b', 'c'];
arr.foo = 'John'

for (const i in arr) {
  console.log(arr[i]);
}

// Result:
// "a"
// "b"
// "c"
// "John"

That looks a bit weird! The for...in loop doesn't just loop through an array, it loops through an objects enumerable properties, which could be the items in an array, but it could be other stuff too.

For this reason, unless your doing something quite niche its probably not the loop you are looking for and is likely to cause you an issue which your objects has one more property than you were expecting.

Pros

  • Can loop through all the enumerable properties on an object.

Cons

  • Looping through all the properties of an object isn't likely what you want.

forEach

As the name implies, a for each loop will iterate through each element in an array. Here's an example:

const arr = ['a', 'b', 'c'];

arr.forEach((i) => {
  console.log(i);
})

// Result:
// "a"
// "b"
// "c"

The forEach function takes an anonymous function as a parameter and will then call that function for each object in the array, passing in the object from the array.

This offers a big improvement over the initial for loop as we have a lot less code to write and we're actually given the object rather than a variable to go an find it.

However there are some downsides due to it effectively being a function call passing an anonymous function to execute.

Firstly you can't stop the forEach part way through. With the others you can use the break keyword to stop the iteration.

Secondly there's added confusion around the scope of what this is. Assuming your function is in a class, unless you use the arrow syntax (as in the example) you won't be able to access any of the other functions in your class as passing a regular function would change the scope.

// This works
class foo
{
myFunction() {
  const arr = ['a', 'b', 'c'];

  arr.forEach((i) => {
    this.outputValue(i)
  })
}

outputValue(x) {
  console.log(x);
}
}

// This Doesn't
class foo
{
myFunction() {
  const arr = ['a', 'b', 'c'];

  arr.forEach(function(i) {
    this.outputValue(i)
  })
}

outputValue(x) {
  console.log(x);
}
}

You also can't use an await within the foreach loop. e.g.

async function run() {
const arr = ['a', 'b', 'c'];
arr.forEach(el => {
  // SyntaxError
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log(el);
});
}

Pros

  • Much shorter to write and easier to read.
  • Iterator provides the object from the array.

Cons

  • Easy to mess up context of this.
  • No way to break the loop.
  • Async/Await doesn't work on functions within the loop.
  • Can only loop through arrays.
  • It's performance is slower (nice article here comparing the performance differences), not to such an extent it would matter on a small object, but large objects could start to take a hit.

for...of

When looping through an array, the for...of loop combines the best of all the other loops. It has the same simple syntax of the for...in loop but instead of enumerating over enumerable properties, it loops through the iterable objects such as the items in an array.

Like the forEach loop you are provided with the object in the array rather than it's index or property name.

const arr = ['a', 'b', 'c'];

for (const i of arr) {
  console.log(i);
}

// Result:
// "a"
// "b"
// "c"

You can also break the loop and access properties outside of the loop.

const stopValue = 'b'
const arr = ['a', 'b', 'c'];

for (const i of arr) {
  console.log(i);
  if (i == stopValue)
      break;
}

// Result:
// "a"
// "b"

Pros

  • Lowest amount of extra code to write.
  • Iterator provides the object.
  • Doesn't use an anonymous function so scope doesn't change.
  • Loop can be stopped as needed.
  • Async still works.
  • Works with more than just arrays.

Cons

  • Have to be looping over the iterable items in an object.
  • Can't easily access the index value.

Conclusion

If you want to iterate through something like an array, for...of would be my recommendation to use. A for...in loop is likely to be less relevant but has its place, and for all other loops which don't relate to the objects in an array a good old for loop still has it's place.