How do you know which one to choose, and when? It can be a minefield for those new to the language.
In this article, we are going to cover 7 of the most popular loops—telling you when and why you would use each. By the end of the article, you will be sure of which loop to use.
To iterate over an Array means to loop through an Array’s contents. We are going to use the 7 types of loops to iterate through the emojis, and print the results to the console.
To get the most out of this article, you will need to understand concepts like Array, String, and Function.
If you don’t, you can learn about them here.
If you do, let’s get started.
Let’s start with the most common and the oldest loop, the For Loop. This is what it looks like:
You can see in the above that between the brackets there are three required attributes, these are:
- Let i = 0; – This creates a new variable that we increment on every loop. “i” represents the Index and we use this variable to access the emoji in the array.
- i < emojis.length; – This is a conditional statement. This code tells the engine to keep looping as long as “i” is less than the Array size.
- i++; – This last attribute is shorthand to increment i. It is the same as writing i = i+1. It will add 1 to “i” on every loop.
In our example, the above loop will loop through each emoji and then print the emoji to the console:
- console.log(emojis[i]) – console.log is how we print to the console. To access each emoji we need to pass the index inside the square brackets.
If you run this code, you will get an output like this:
Sometimes you need to loop until you find an element in the Array. To do this we can use a Break statement.
Break will stop the For loop from running. This is useful when you are trying to find a value in a large Array. For example, say that we were not sure where the skull was in our Array and we wanted to loop until we found it.
Well, we could write code like this:
As soon as we match the skull the loop stops. Can you guess what the console output will be? Here it is:
What if we wanted to perform an operation on all the values in the Array except one? In this case, we could use Continue.
Continue is like a Break statement but instead of stopping the loop it can skip or “jump over” an item in the array.
This time we are going to write the code so that when we find a skull, we skip it and we won’t print it to the console:
As you can see, the code is almost the same as the prior example, except that this time we have replaced Break with Continue. The outcome is different:
The skull has not been printed as expected. You can use Continue to filter an Array and only perform an operation on some of the items.
We have looked at traditional For loops, but there are shorter versions. We can use a For..in loop to loop through an Array like this:
This is shorter code and there is no need to increment the index using the i++ code. So why not use this loop all the time?
There is a problem with For..in.
You see, it is possible to extend a built-in object like Array. For example, I can create a custom operation on an Array, like this:
Now when you run the code this is the output:
The `foo` function is part of the loop! For this reason, you should never use For..in in your code.
We have discussed the basic For loops—next, we will look at While loops.
A While Loop will continue to loop while a condition is true.
For example, the below code will loop while “i” is less than the Array size:
We are doing the same thing as we were in the For loop:
- i = 0 – Creating an index variable and setting it to 0.
- i < emojis.length – Looping while i is less than emojis.length
- console.log(emojis[i]) – printing each emoji String to the console.
- i++ – Incrementing the index by 1 on each loop.
This code will print all the emojis.
Why would you use a While loop over a For loop?
For each loop, we check the condition (noFox) and if it is ‘true,’ then the loop continues. As soon as ‘noFox’ is set to false the loop will stop. This is like the break statement For loop we used above.
What if you wanted to check the conditional after the loop? Well, in that case, you need a Do/While loop.
This loop is almost identical to the while loop, except the condition check is at the end. This is what the code will look like:
The code will run in this flow:
- Set the index to 0
- Print the first element in the Array using console.log
- Add 1 to the index
- Then check is index is still less than the size of the Array
For both of these are operations, you can call on an Array. For the emojis Array, it would look like this:
Browser support for these ES5 methods is good, so you can use them for your front-end code.
Let’s look at these more in depth.
forEach is a function added to the Array type. The function takes a callback function, which is a block of code, like this:
For every value inside the Array, it will run the callback block you pass inside the brackets. This is a nice way to do For loops in ES5.
If forEach is available, then this is the recommended way to do a loop.
You can loop using a Map function the same way as forEach by passing a callback. The map function then calls this callback for every item in the Array.
The difference with Map is that it returns an Array. This function can convert the contents of one Array to another. For example, if we wanted to create a new Array with all the emojis as skulls, we could run this code:
Use this Loop when you need to create a new array from an existing one. This can be a very powerful loop when combined with reduce.
The last loop we are going to look at is part of ES6.
This is the For..of loop.
This loop addresses the shortcomings of “For..In” and has similar code syntax.
The browser support for ES6 is getting better yet IE is a bit behind. This means you may not be able to use For..of if you need to support the IE browser.
Like the For..of loop the code looks like this:
This does not have the same problem as the For..in loop. Anything added to the Array will not appear in the loop. If you are in an ES6 environment, then you can and should use this loop.
If you do not have ES5 or ES6, then you can use the traditional For loop or a While loop.
If you have ES5, then you can use either forEach or Map. If you are only supporting the latest browsers and have ES6, then you can look at using For..of.
Whatever you do, don’t use For..in!
About the Author: Steve Keep
Steve Keep (@pagedart) has worked in IT for over two decades, mostly as a software developer. He’s a web enthusiast who finds time to create sites using the latest technology. From IoT, mobile and AI he has been lucky enough to have worked with it all. He blogs about the web at pagedart.com.
This is my first time learning about these loops. Very interesting. Thanks for the well article Steve and your detailed explanation of how to make them work.
Is it best to use “var” or “let” in for loop iterations or does it even matter?