DEV Community

Carl-Lundgren
Carl-Lundgren

Posted on

For Loops and Beyond (in JavaScript)

This may seem obvious but loops are a very useful tool for code. They allow you to do things that you wouldn't be able to do at all otherwise and let you do other things far easier than you could using other methods. While there are many different types of loops and they all have uses, we'll be focusing on for loops and it's many variations in this post.

So, lets get started with the basics
let i = 0;
for (i; i < 4; i++){
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

So what does the code mean? Basically, in English, it's saying "This is what i is. For as long as i is less than 4, print out in the console what i is. After i has been printed increase i by 1". When this code runs it would print out 0, 1, 2, and 3, each on separate lines. This is about the bare minimum you can do with and for a basic for loop, but is a good example for understanding the basics. Now lets break it down a bit more.

A for loop requires that you put in three different parts.

  1. The first part (which in this case is i) establishes the variable (i) that we're using to determine how many times the loop is running. The variable being used in this part has to have it's value be a number but it doesn't have to be declared beforehand. If the variable's value hasn't been declared then you can declare it here (ex. for (i = 0; ...)) and even if the variable's value has been declared you can change it's value to something else here (ex. for (i = 3; ...)). You can even declare a variable that hasn't been declared anywhere else and you don't even have to use let or var (ex. for (num = 0; ...)). One quick side note, you can't use any variable declared with const because the variable will be being changed in the for loop.

  2. The second part (i < 4) determines in what instances the code in the loop runs. For the example above the code only runs if i < 4 but you could have it only run if i <= 4, or if i = 0, or if i > 6, etc. Be mindful that if the situation is something that never will occur (like i = 4 even though i is declared as 0) then the code in the loop will never run, and if the situation is something that will always be the case (like i > 2 when i is 4 and is increasing in value) then the loop will run forever, although this is something that also ties into the third part.

  3. Part three is how you are modifying the variable (i++ for our example). You can modify the variable in a bunch of ways, but some of the most common ones are ++ which increases the variable by one, and -- which decreases it by one. You can even change the variable inside of the loop. Whenever you're changing the variable, make sure that it doesn't make the loop go infinite and more generally check that you're both modifying the variable and going through the loop the number of times that you're wanting.

//

While for loops allow you to do a lot of things there are some tools related to for loops that are designed for iteration (aka going through a thing for each thing inside that thing) and, even though for loops can work in their place, they do it a lot cleaner. The ones will be going over here are: for...in, for...of, and forEach().

for...in

for...in is used for iterating over objects. A very simple, but very useful thing to do so efficiently.

const object = {things: "stuff", number: 7, color: "blue"};

for (const key in object) {
  console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

The above will log in order: things, number, and color, but it will not log stuff, 7, or blue. In order for it to print the latter you'd need it to be console.log(object[key]); because of how sorting through objects works (we'll not be getting into that here). Technically, for...in can iterate over arrays, but you do not want to do this as it can cause various problems including, but not limited to, mixing up the order of the array. If you're working with an array then you'll want one of the following two instead.

for...of

for...of has basically the same formatting as for...in, but is used for arrays and not objects.

const array = ["red", "blue", "green"];

for (const element of array) {
  console.log(element);
}
Enter fullscreen mode Exit fullscreen mode

This would log red, then blue, then green. Interesting thing about for...of is that it can be used on more than just arrays, it can also be used on strings. for (const element of "red") {console.log(element);} would log r, e, d.

forEach()

forEach() is different from the other two as far as formatting, but like for...of, it iterates through arrays.

const array = ["red", "blue", "green"];

array.forEach(function (element){
  console.log(element);
});
Enter fullscreen mode Exit fullscreen mode

forEach() passes in a function and runs that function for each element (aka thing) in the array. For those of you familiar with arrow functions, below is another, probably more common, way to write this. For those of who aren't, the above and below are the same and both log the same thing as the for...of did.

const array = ["red", "blue", "green"];

array.forEach(element => console.log(element));
Enter fullscreen mode Exit fullscreen mode

As far as the differences between for..of and forEach() there are a handful, with for...of being able to be affected in a handful of ways that forEach() can't, but for the most part the choice between the two comes down to comfort and personal preference for the specific instance. Basically, most the time just use what you're more confident with.

//

You should now have a basic understanding of for loops and some of it's variants (assuming I've done my job right). I challenge you to use some of these in your own code, and if you want you can even push yourself by messing around with nesting for all of these different concepts, although that will make it more complicated. Good luck and have fun.

Top comments (0)