DEV Community

Preston Lamb
Preston Lamb

Posted on • Originally published at prestonlamb.com on

JavaScript Loops

tldr;

Any time we need to run the same code multiple times for a set of data, and don’t want to just repeat the code over and over again, a loop is a perfect option. There are multiple types of loops, all of which accomplish a similar function but that go about it in a different manner. There are for loops, for ... of loops, for ... in loops, and more. We’ll go over those as well as using break and continue in your loop.

Introduction

Before we get started on the types of loops there are, we need to understand what things can be looped over. In JavaScript, certain things are iterable; that means they can be looped over. Iterable objects include arrays, the keys of an object, strings, and Sets, for example. The most common iterables, though, are arrays and that’s what the majority of the examples in this article will focus on.

Also, some loops don’t iterate over anything, so they don’t need an iterable to be used. We’ll look at those loops as well.

for Loop

Let’s start with the basic loop. You’re probably familiar with it, especially if you’re coming from another language. In a for loop, you create a local variable that acts as the index and counter in the loop. You then provide a comparison which, when true, will end the loop. Finally, you provide a manner in which the index will increment each time through. Let’s look at an example.

const arr = [1, 2, 3];

for(let i = 0; i < arr.length; i++) {
    console.log(arr[i]); // 1 2 3
}
Enter fullscreen mode Exit fullscreen mode

It’s important to use let or var, and not const. If you use const the variable can’t be reassigned and you’ll get an error. The convention is to start your local index variable at 0, as JavaScript indices are 0 based. On the comparison, if you want to access each item in the array, you need to go until the local variable is less than the length of the array. If you go any further, you’ll go beyond the limits of the array. Finally, i++ is a short way of incrementing the local variable. You could increment by two each time if you want, or whatever you choose.

Once inside the loop, you can do any amount of code as you’d like. If you want to access the item at the given index, you can do so by using index notation, or arr[i].

for ... of

The for ... of loop is similar to the for loop, but it will loop over each item in the array. You don’t have to tell it how far to go, though, as it will do so automatically. You’ll again create a local variable, though this time you can use const (and I usually do except on the rare occasion I need to reassign the value of the local variable). Let’s look at an example.

const arr = [1, 2, 3];

for(const item of arr) {
    console.log(item); // 1 2 3
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we don’t need to use index notation to get the item in the array; it’s just given to us each time through the array. It could be a character in a string, an item in an array, or whatever else is next in the iterable. This is my preferred method of looping over the items in an array. I like how concise and explicit it is.

for ... in

The for ... in loop is very similar to the for ... of loop. The only difference is that instead of giving you the item in the array, it gives you the index each time through the loop.

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

for (const i in arr) {
    console.log(i); // 0 1 2
}
Enter fullscreen mode Exit fullscreen mode

This loop is also great if you want to loop over the keys of an object.

const obj = {
    name: 'Preston',
    age: 31
}

for (const key in obj) {
    console.log(key); // name age
}
Enter fullscreen mode Exit fullscreen mode

This is another handy loop, but I find it most often useful when I need to loop over the keys of an object for one reason or another.

.forEach

Any object in JavaScript that is array-like (arrays, and Sets for example) have a .forEach method on the prototype. The method takes a function as the argument, and loops over each item in the array. In that manner it’s like the for ... of loop. Let’s look at an example.

const arr = [1,2,3];

arr.forEach((item) => console.log(item)); // 1 2 3
// or
arr.forEach(function(item) {
    console.log(item); // 1 2 3
})
Enter fullscreen mode Exit fullscreen mode

There is no functional difference between for ... of and .forEach. It’s mostly user preference. I like the for ... of option personally, but you can use what you prefer.

while and do ... while

A while loop is another useful loop, although I use it much, much less than any of the three previous loops. In this loop, you provide a condition that, until it evaluates as false, will continue running. In this case, you don’t need an iterable to loop over. Let’s look at an example.

while(expressionIsTrue) {
    // Do whatever you want
}
Enter fullscreen mode Exit fullscreen mode

The do ... while loop is almost the exact same. The only difference is the syntax of how it’s started.

do {
    // Do whatever you want
} while (expressionIsTrue)
Enter fullscreen mode Exit fullscreen mode

Stopping Loops

There are times when we don’t want to go through every iteration of the loop, or we want to skip a part of the loop. How can we do that? There are two keywords that are helpful in these situations: break and continue. break ends a loop and jumps out of it. continue skips one pass through the loop. Let’s look at an example of each.

const arr = [1,2,3,4,5]
for (let i of arr) {
  if (i === 3) {
    break;
  }
  console.log(i); // 1 2
}

for (let i of arr) {
  if (i === 3) {
    continue;
  }
  console.log(i); // 1 2 4 5
}
Enter fullscreen mode Exit fullscreen mode

These two keywords can be used in any type of loop. If you need to stop looping, or just skip one iteration, break and continue are your friends.

Conclusion

Looping over items, or repeating code in some manner, is a common piece of functionality used in almost all applications. Knowing the types of loops there are and when to use them is vital to using the correct tool for the job.

Top comments (0)