How to use for and while loops in JavaScript

Last updated: July 19, 2022.

Very often when working in Javascript, we come across repetitive tasks. For example, we may want to:

  • Populate a table with a long list of values stored in an arrary
  • Change the appearance of all DOM elements containing a certain class name
  • Repeatedly appending items to the DOM fetched from an API

We can often do this work by hand. But it would likely be error-prone and time-consuming. With loops we can perform a repetitive task on a list in milliseconds when a human would take hours!

And often we cannot do it by hand: for example, is we fetch data from an API at the beginning of our script, especially if there is variation in the number of returned items (we will return to this later). We need to do this dynamically in our script.

With loops, we have two options: for and while.

Writing loops

The “for” loop

By far the most commonly used loop is the for loop. To write one, we must specify three conditions in the following order:

  1. The starting value of the so-called ‘looping’ variable
  2. The value of the looping variable that must be reached for the loop to end (often the length of an array)
  3. What happens to the value of the looping variable at the end of each loop

The looping variable is simply a variable that is created when first writing the loop and changes it value each time the loop is completed (i.e. on each loop iteration) to a new value determined by us. Most commonly, we would increase the value of the looping variable by 1 each time to work through a list of items.

To make this more concrete: we have a list of 20 blog items and want to output these to a page. We could achieve this by writing the following logic into our loop:

  1. Setting the starting value of the looping variable to 0
  2. Specifying that the loop should carry on until the value of the looping variable reaches 20
  3. Setting the value of the looping variable to increase by 1 for each iteration of the loop

This way, the loop will execute whatever we specify 20 times. In this case, it will get each blog and append it to the DOM. Exactly the same logic of programming a looping variables applies no matter what the task

Writing a “for” loop

So far, we have described the logic of a for loop. Below is it’s basic syntax:

for (let i = 0; i < 5; i++) {   // Looping variable specifications
  alert(i); // The loop task

In the above example, our looping variables begins at 0 (let i = 0), the loop ends when the looping variable reaches 20 (i < 20) and it increases by 1 each time (i++). And each time the loop iterates, we create an alert displaying the value of the looping variable during the iteration. Being able to access the value of the looping variable in the loop task is extremely useful: for example, we can access item 0 from a list in the first loop, item 1 in the second iteration, 2 in the third, etc. Note that each condition must be separated by a semi-colon.

Let’s now look at a more concrete, common task.

Example: looping through an array and writing to the DOM

Below is a hardcoded list of countries saved in the variable countryList. More commonly, we would retrieve such an array dynamically from an API.

const countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];

We also have the following HTML document:

<div id = "countryContainer">
   <h2>Below all the countries of this world</h2>
      <table id ="countryTable">

You will notice here that our table is empty. We woud like to loop through countryList and add each country inside the <table> element within its own row. So we end up a list of countries in a table, each contained in a single row.

We can do this with the following Javascript code:

// countryList already entered above

const countryTable = document.getElementById('countryContainer')
for (let i = 0; i < countryList.length; i++) {
    let newRow = document.createElement('tr');  // create row element
    let country = newRow.textContent = countryList[i]; //append country [i] to row
    countryTable.appendChild(newRow); //append row to the table   

So our looping variable starts at 0; the loop breaks when the loop variable is less than countryList.length; and increases by 1 for each iteration.

Note that we use the looping variable within the task. Each time we run the loop, we ask for element i to be appended to a new row. And because the looping variable increases by 1 each loop, we work, one-by-one, through the list.

Also, note the i < countryList.length syntax. Using the length method in this way is very common and useful. We tell our loop to stop when the looping variable reaches the end of the array. This is much better than hardcoding this value because the list length may change over time. If this occurs and we hardcode it, Javascript will throw and error. However, if we use the length method, our loop will adapt to the list length.

Below is a live example of this code in action:

An alternative: the “while” loop

Another way to perform the same action using a slightly different syntax is to write a while loop:

let i = 0; // Looping variable starting value
while (i < 5) {   // Loop end condition
  alert(i) // Loop task
  i++; // Change to looping variable at the end of each iteration

As you can see, we specify everything we would do in a for loop in a different order:

  1. The starting value of the looping variable (i) is specified before the loop
  2. The value of the looping variable when the loop should end is specified at the start of the loop
  3. The change in value of the looping variable for each task completion comes last

Skipping and breaking a loop

Sometimes, we may want to skip an iteration of a loop or break the loop execution entirely. For example, we may want either of these two to occur when a null value is encountered. We can set this condition manually.

To do so, we use the continue and break syntax.

Here is an example of using continue:

const array = ["John", "Kevin", "Julie", null, "Sharon"]

let i = -1;
while (i < array.length) {
   if (array[i] == null) continue;

By typing if (array[i] == null) continue, we are asking Javascript to skip the rest of the code in a loop if the array entry in position i is null. So here, the fourth element (null) is skipped and we still see “Sharon” in the final alert.

Note here that i++ is now at the beginning of the loop. This is simply to make the code work for this example but also shows the flexibility of a while loop: the looping variable change command can be placed anywhere inside the loop. Also note that i is now created with a starting value of -1 so it is 0 in the first iteration of the loop.

Finally, an example of the break command:

const array = ["John", "Kevin", "Julie", null, "Sharon"]

for (let i = 0; i < array.length; i++) {
   if (array[i] == null) break;

In this example, we stop the loop entirely when we encounter a null value in the array. So when we run this code, we don’t see the name Sharon at all.

Is it better to use a “for” or “while” loop?

As should already be clear from reading the article, for and while loops do identical actions but with a difference in syntax. The main difference is that for loops can be slightly easier to read because all three key conditions are declared at the start of the loop. However, while loops are more flexible because these condition can be set in different places.

As such, as a general rule of thumb, for loops should be used for simple loops. Whereas it is better to use while loops when loop rules become more complex and conditional.