Understanding Loops In JavaScript

Understanding Loops In JavaScript

Blake Yeboah
ยทDec 1, 2021ยท

7 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Types of Loops In JavaScript
  • The for loop
  • The for/in loop
  • The while loop
  • The do while loop
  • The forEach loop
  • Take Away

There are many kinds of loops in JavaScript. From for loops to while loops, this article covers them all and will teach you when and why to use each.

This article is completely beginner friendly, so whether you are coming from a different language looking to learn the syntax or learning JavaScript as your first language, you will be able to understand clearly.

Lets start off by listing the different types of loop and exactly what they do.

Types of Loops In JavaScript

  • for - simply runs a block of code a certain number of types
  • for/in - loops through properties of an object or indexes of an array
  • while - runs a block of code while a condition is true
  • do/while - same as while loop however runs code once before checking condition
  • forEach - loops through an array

The for loop

The for loop is a staple in many programming languages. It is present in some form in almost every programming language out there making it good to have an understanding of it in your toolbelt.

Lets say we want to log the numbers 1 - 5 in the console. A for loop is a very simple solution since it will allow us to loop through exactly 5 times and log each number as we go.

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

The above is an example of a for loop which simply logs the numbers 1 till 5 in the console. A for loop consists of 5 parts.

The first is the keyword for which declares a for loop. This is followed by 3 statements in a pair of parenthesis. These include let i = 1 which sets a counter for the loop and is run prior to the code being executed.

The second statement is the condition for executing the code block. In this case, i <= 5 which means it will run while the variable i is less than or equal to 5.

The third statement is executed every time after the code block has been executed. In this case, after the code runs i will increment by one (i++).

i++ is the equivalent of i = i + 1, just in shorter syntax.

The final part of the for loop is the code block in between curly braces ({ & }). In this case, it is simply logging the value of i to the console (console.log(i)).

for loops can be used to run code a certain amount of times, as done in this case. However, for loops can also be used to iterate over an array. For example, lets say we have an array of animals:

const animals = ["dog", "cat", "fish", "turtle", "cow", "horse"]

We can use a for loop to iterate over the array and do anything we want with each animal:

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

In the above example, we are looping through the animals array and logging each animal to the console. We set i to 0 since arrays are zero-based and by setting the condition to i < animals.length it will stop when we reach the end of the array. To select the item the loop is currently on, we can use i like this: animals[i].

That just about covers the for loop, lets move on to the for/in loop which is similar however has a different purpose.

The for/in loop

The for/in loop is also declared with the for keyword, however in the parenthesis, it only includes one statement with the keyword in.

The for/in loop can be used to loop through properties of an object. Lets say we have an object called person:

const person = {
   firstName: "Blake",
   middleName: "Kofi",
   lastName: "Yeboah"
}

This person has a firstName, middleName, and lastName which I have used my names as the values. Lets say we wanted to loop through the properties of this object.

We can use a for/in loop:

for (let property in person) {
   console.log(property)
}

This loops through each property of the object so the value of the property variable will equal firstName, then middleName, and finally lastName.

If we wanted to retrieve the values of these properties:

for (let property in person) {
   const name = person[property]
   console.log(name)
}

We use the person[property] syntax to retrieve each name from the object.

In addition to looping through an object's properties, for/in loops can be used to loop through an array. For example, lets use the same animals array and loop through it:

for (let i in animals) {
   const currentAnimal = animals[i]
   console.log(currentAnimal)
}

This loop iterates through the array and the index is stored in i or whatever you decide to call the variable. We can then retrieve the current index's item with:

const currentAnimal = animals[i]

The while loop

The while loop simply runs a block of code while a certain condition is true. The condition is passed in parenthesis after the while keyword. An example of a while loop looks like this:

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

In the above example, we are simply running a loop 5 times and printing numbers from 0 till 4. The condition of this while loop is i < 5 which means run the code while i is less than 5. We defined i in the first line of code prior to the loop and set its value to 0. The final line of code in the code block, i++; increments i so that the every time the loop runs i is increased by 1.

Its very important to increment i otherwise the loop will be endless and will keep running the code non-stop.

The do while loop

The do while loop is very similar to the while loop however the code block is run before the condition is checked. This means that the even if the condition is false the code block will run once. A do while loop looks like this:

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

Remember the increment i++ to avoid an endless loop.

The do while loop can be used in replace of a regular while loop provided its fine for the code to run before the condition is checked. For example, in the loop above, its completely viable to replace the while loop with the do while loop.

However, if the condition is checking if a variable exists, and this variable is used in the code block, it would be a bad idea to use a do while loop instead of a while loop.

The forEach loop

The final loop we will be covering is the forEach loop. This loop is a high order method on arrays in JavaScript. This means the only purpose of this loop is to loop through an array. Lets use the animal array as an example again. For reference:

const animals = ["dog", "cat", "fish", "turtle", "cow", "horse"]

We can loop through it with a forEach loop by calling the .forEach method:

animals.forEach(function(animal) {
   console.log(animal);
})

The .forEach method takes in a callback function that has access to the current item its on in the array (animal in this case). This callback function also has access to the index as a separate parameter after the animal parameter. This method is also covered in my JavaScript High Order Array Methods article which covers other methods relating to arrays..

The sole purpose of this loop is to iterate over an array. I personally think this is one of the most important types of loops to learn since iterating over an array is very common in most applications.

Take Away

If you've reached the end of this article, congratulations! You now understand 5 different types of loops in JavaScript and can begin implementing them in your code. Make sure you are practicing using these loops to further develop your understanding and make you a better developer.

๐Ÿ‘Œ Thanks for reading this article!

If you like what I do and would love to see more related content, follow me on my other social platforms:

GitHub: Blake-K-Yeboah

LinkedIn: Blake-K-Yeboah

You can also show your support by buying me a coffee ๐Ÿ˜ƒ

Did you find this article valuable?

Support Blake Yeboah by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this