Choosing the Right Loop in JavaScript

In JavaScript, you have a variety of loop types at your disposal, including for, while, do...while, and for...in/for...of. Although you're comfortable with the implementation of each loop type, you struggle to determine when and why to use each one.

The choice of which loop to use often depends on the specific requirements of your situation. In this article, I'll offer insights to help you understand when it's best to use each type of loop.

For Loop

This is the most common loop, used when you know the exact number of iterations. It's great for iterating over arrays when you need to reference the index.

for (let i = 0; i < 5; i++) {
  console.log(i); // Output: 0, 1, 2, 3, 4
}

While Loop

This is used when you don't know the number of iterations, but you have a condition that ends the loop. It's useful when the condition depends on the code within the loop.

let i = 0;
while (i < 5) {
  console.log(i); // Output: 0, 1, 2, 3, 4
  i++;
}

Do...While Loop

Similar to the while loop, but the code block is executed at least once before the condition is checked. This is useful when the loop must execute at least once.

let i = 0;
do {
  console.log(i); // Output: 0
  i++;
} while (i < 0);

For...In Loop

This is used for looping over the properties of an object. It's not recommended for arrays as the order is not guaranteed.

const obj = { a: 1, b: 2, c: 3 };
for (let prop in obj) {
  console.log(`${prop}: ${obj[prop]}`); // Output: "a: 1", "b: 2", "c: 3"
}

For...Of Loop

This is used for looping over iterable objects like arrays, strings, or NodeLists. It's great for when you don't need the index, just the values.

const arr = [1, 2, 3];
for (let value of arr) {
  console.log(value); // Output: 1, 2, 3
}

In summary, the choice of loop depends on what you're trying to achieve. Consider the number of iterations, whether you need the index or just the values, and whether you're working with arrays or objects.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda