The Talent500 Blog
A Complete Guide to Loops and their Types in JavaScript 1

A Complete Guide to Loops and their Types in JavaScript

JavaScript is a versatile programming language that allows developers to create interactive and dynamic web applications. One of the fundamental programming concepts in JavaScript, as in many other languages, is the use of loops. 

Loops are a powerful tool that allows developers to repeat a block of code multiple times, which can save time and reduce the amount of code needed. 

In JavaScript, there are several types of loops that can be used depending on the situation and the desired outcome. In this article, we will explore the different types of loops in JavaScript and how they can be used effectively in web development. Whether you are a beginner or an experienced developer, understanding these loops can help you write more efficient and effective code. 

So, let’s dive in and explore the different types of loops in JavaScript.

Overview

A loop in JavaScript allows us to execute a block of code repeatedly. It is used to automate repetitive tasks and perform complex operations with ease. Loops are an essential part of any programming language, including JavaScript, and play a vital role in developing dynamic and interactive web pages.

JavaScript provides several loops, including for loops, while loops, do-while loops, for-in loops, etc. Each type of loop has its own unique syntax and functionality, making it suitable for specific use cases.

Let’s suppose we have four HTML elements and we want to listen to some events in each of the boxes. Then, how can we achieve this goal?

A Complete Guide to Loops and their Types in JavaScript 2

Yes, in this case, we can use the power of loops instead of listening to events in each of the boxes individually. We can listen to events on all of the boxes by looping through the HTML elements.

HTML Code:

    <div>Box-1</div>

    <div>Box-2</div>

    <div>Box-3</div>

    <div>Box-4</div>

In the above code snippet, there are four HTML elements, and we want to listen to a click event for all the boxes. So instead of listening to events individually, we can select all HTML elements using JavaScript selectors, and it returns a NodeList (in other words, a list of HTML elements).

  const box = document.querySelectorAll(div);

  console.log(box); //NodeList (like an array)

In the above code snippet, I have selected all div HTML elements in JavaScript using the querySelectorAll() method, which returns a NodeList.

 

Now, this NodeList can be easily iterated using the built-in JavaScript loops, I am going to use a type of loop that is called forEach. Have a look at the below code snippet and codepen link as well. Do not worry; we are going to take a closer look at this below-loop code later in this article.

 

  const box = document.querySelectorAll(div);

  console.log(box); //NodeList(like an array)

  box.forEach(function (element) {

  box.addEventListener(click, function () {

       alert(Button clicked!);

    });

 });

 

Play with the codepen link: Click here

 

As you can see, loops help us to write quick and concise code. If there are no loops in JavaScript, then we need to listen to those events individually, which is time-consuming and inefficient at the same time. That’s why in this blog we are going to see the different types of loops in JavaScript.

For Loop

For loop allows us to repeat a block of code a specific number of times. It’s commonly used for iterating over arrays and other collections of data, and it can be customized with initialization, condition, and increment/decrement statements.

This is the following syntax of the for loop:

      for(initialization; condition; increment/decrement){

        // Lines of code to be executed.

      }

Where, 

  • Initialization: This statement is executed before the loop starts. It is usually used to declare and initialize a counter variable.
  • condition: The condition statement is evaluated before each iteration of the loop. If the condition is true, the code block is executed. If the condition is false, the loop exits and jumps to the next line of code.
  • increment/decrement: The increment or decrement statement is executed after each iteration of the loop. This is usually used to update the counter variable.

 

Suppose we have an array of objects (see the below code) and want to display this data on a web page in a tabular form. So instead of displaying individually, we can use a loop to show this data on a page.

Why am I using this type of format as an example? Because when we fetch data from the remote server or APIs, they will provide data similar to this format. That’s why I am using an example to mimic the data coming from an API.

 const userData = [

 { id: 1, user: Ajay, userAddress: Patna },

 { id: 2, user: Pranav, userAddress: Banglore},

 { id: 3, user: Anas, userAddress: Delhi },

];

console.log(userData); //Array of objects

Now we have an array, and there are three items kept inside this array. The index of the first object is 0, for the second object it is 1, and for the last object, it is 3. Also, each object has three key-value pairs: id, user, and userAddresses, as you can see in the above code snippet.

Now we can easily display this data on the web pages in tabular form using for loops, as shown in the below image. However, this can be done using the map() method as well; I have covered this topic in detail. So please refer to this article from talent500.

A Complete Guide to Loops and their Types in JavaScript 3
HTML Code

   <h1>Fetching user data from the remote server…</h1>

    <hr />

    <table>

      <thead>

        <tr>

          <th>Id</th>

          <th>Name</th>

          <th>Address</th>

        </tr>

      </thead>

      <tbody class=dynamic>

        <!– <tr”>

          <td>dummy</td>

          <td>dummy</td>

          <td>dummy</td>

        </tr> –>

      </tbody>

    </table>

 

JavaScript code:

 const userData = [

  { id: 111, user: Ajay, userAddress: Patna },

  { id: 112, user: Pranav, userAddress:Bangalore },

  { id: 113, user: Anas, userAddress: Delhi },

      ];

      console.log(userData); //Array of objects

      let data = “”; //Empty data

      for (let i = 0; i < userData.length; i++) {

        data += ` <tr>

          <td>${userData[i].id}</td>

          <td>${userData[i].user}</td>

          <td>${userData[i].userAddress}</td>

        </tr>`;

      }

      document

        .querySelector(.dynamic)

        .insertAdjacentHTML(beforebegin, data);

 

In the JavaScript code, I looped through all objects inside the array and displayed the dynamic data on the web page.

 

Play with the codepen link: Click here

While loop

A while loop is another type of loop in JavaScript that allows a block of code to be executed continually while a particular condition remains true. The syntax of a while loop in JavaScript is as follows:

      while (condition) {

        // Lines of code

      }

The condition is an expression that is evaluated at the start of each iteration of the loop. If the condition evaluates to true, the code inside the loop will be executed. After the code is executed, the condition will be evaluated again, and if it still evaluates to true, the code is executed again. This process continues until the condition is evaluated as false.

Let’s iterate the above array of objects using a while loop.

      let data = “”; //Empty data

      let item = 0; // Let suppose the length of the array = 0

      while (item < userData.length) {

        data += ` <tr>

          <td>${userData[item].id}</td>

          <td>${userData[item].user}</td>

          <td>${userData[item].userAddress}</td>

        </tr>`;

        item++;

      }

 

The JavaScript code is used to iterate through an array of user data and generate an HTML table row (tr) for each element of the array.

 

First things first, I have initializes an empty string called data that will store the HTML table rows as they are generated.

 

Then I created a variable called an item that was initialised with 0. which will be used as an index to iterate through the userData array.

 

Now, the userData array is going to be iterated one by one using a while loop, that will iterate over each element in the userData array until the item index is equal to the length of the array.

 

Then,  generates an HTML table row (tr) for the current element in the userData array and appends it to the data string. The table row includes three table cells (td) that display the ‘id’, ‘user’, and ‘userAddress’ objects properties of the current element in the array. 

 

Finally, item++ increments the item index by 1 to move to the next element in the userData array. Once the while loop completes, the data string will contain all the HTML table rows generated from the userData array, which can be inserted into an HTML table to display the user data.

 

Play with the codepen link: Click here

Do-while Loop

A do-while is also a type of loop that executes a block of code at least once, and then repeatedly executes the block of code as long as a specified condition is true.

Here, the following sytax of the do-while loop:

      do {

        //code block to be executed

      } while (condition);

 

The block of the do statement will be executed first. Then, the while statement is evaluated. If the condition is true, the code block is executed again. If the condition is false, the loop ends and the program continues with the next statement.

 

      const userData = [

        { id: 111, user: Ajay, userAddress: Patna },

        { id: 112, user: Pranav, userAddress: Banglore },

        { id: 113, user: Anas, userAddress: Delhi },

      ];

      let i = 0,

        data = “”;

      do {

        data += ` <tr>

          <td>${userData[i].id}</td>

          <td>${userData[i].user}</td>

          <td>${userData[i].userAddress}</td>

        </tr>`;

        i++;

      } while (i < userData.length);

      document

        .querySelector(.dynamic)

        .insertAdjacentHTML(beforebegin, data);

 

One of the main advantages of a do-while loop is that the code block is guaranteed to be executed at least once, regardless of the initial condition. 

 

This can be useful in situations where we want to ensure that a certain block of code runs at least once before checking a condition.

Play with the codepen link: Click here

 

forEach Loop

A forEach loop is a higher-order function that allows us to iterate over the elements of an array and perform a specific action on each element.

 

The forEach loop takes a callback function as its argument, which is executed for each element of the array. Here is the following syntax of the forEach loop:

 arr.forEach(function (currentValue, index, array) {

   // code to execute for each element

  });

 

The arr is the array that the loop is iterating over and forEach loop takes a callback function that is executed for each element of the array. The callback function takes three parameters:

  • currentValue: The current element represents each element in the loop.
  • index: It is the index of the current element of the array.
  • array: It is the original array that is being iterated over.

I have already shared an example of the forEach() method with you in the first section of this article, but you can also see the below example as being more simple.

      const arr = [10, 20, 30, 40, 50];

      arr.forEach((item) => console.log(item * 2));

 

In the above code snippets, there is an array called arr, and this array is iterating using the forEach method. This method takes a callback function that will execute for all the items in the array.

The item parameter represents each element of the array, and then we can do any operations using this item element.

Play with the codepen link: Click here

For-in Loop

A for-in loop is used to iterate over the properties of an object. It allows us to execute a block of code for each property in the object. Here is the syntax of this loop:

   for (key in object) {

       // code to be executed

     }

Syntax explained:

  • key: This is a key that is used to hold the name of each property in the object as the loop iterates over them. We can choose any valid variable name as the key of the object.
  • in: This is a keyword used to separate the variable from the object and indicates that the loop will iterate over the properties of the object.
  • object: This is the object that the loop will iterate over. It can be any object that has properties.

See the below code for more clarity:

      const user = { name: Ajay, Add: Patna, PhNo: +91 432423432 };

      for (const key in user) {

        console.log(key); //Returns the property name of the object.

        console.log(user[key]); //Returns the values of the object’s properties.

      }

Play with the codepen link: Click here

For-of Loop

A for-of is also a type of loop which provides an easy way to iterate over items of an iterable object. It is a more straightforward and expressive way to iterate over iterable objects.

Here is the syntax of the for-of loop:

      for (item of iterable) {

        // code to be executed for each element of iterable

      }

Syntax explained:

  • item: This is a variable that will be assigned to each element of the iterable object during each iteration of the loop. 
  • iterable: This is an object that is iterable, which means it has a collection of elements that can be accessed one by one using the for-of loop.

Here is the real-world example of for-of loop:

      const userData = [

        { id: 111, user: Ajay, userAddress: Patna },

        { id: 112, user: Pranav, userAddress: Banglore },

        { id: 113, user: Anas, userAddress: Delhi },

      ];

      let data = “”;

      for (const item of userData) {

        data += ` <tr>

          <td>${item.id}</td>

          <td>${item.user}</td>

          <td>${item.userAddress}</td>

        </tr>`;

      }

In the above code snippets, the userData object will be iterated using the for-of loop, which returns an individual object each time. We can then easily append this data to the web page.

Play with the codepen link: Click here

Conclusion

In conclusion, JavaScript provides several types of loops, as we saw in the above discussion, which is used for iterating over collections of data or repeating a specific number of times. Iterable objects can be arrays, strings, maps, sets, and other objects. One more thing: there are multiple array methods in JavaScript that act like a loop, meaning they also execute callback functions like the forEach() loop. So please take care of these things as well.

Also, if you are looking for a JavaScript job, so please search them on talent500.co

5+
Ajay Yadav

Ajay Yadav

I am a frontend developer and am eager to deep dive into the technologies through my content.

Add comment