Loops in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

This post is a bit long because I tried to explain JavaScript loops in a way that I hope would make it much easier to understand. I'd be so happy if you read it to the end, and gain some value from it. Thank you very much 🤗.


What is a loop?

A loop is a sequence of instructions, repeated until a certain condition is reached.

Loops are used in JavaScript to perform repeated tasks based on a condition, which typically returns true or false when analysed. A loop will continue to run as long as the condition returns true, and when the condition returns false, the loop stops.


Types of Loops

Loops can be classified into two major types, entry-controlled loops and exit-controlled loops.

In entry-controlled loops, the test condition is checked first, then the body of the loop is executed if the condition is true. If the test condition is false, the body of the loop will not be executed.
This type of loop is usually used when it is mandatory to check the test condition before executing the body of the loop. Examples of entry-controlled loops are while loop and for loop.

In exit-controlled loops, the body of the loop is executed first, and then the condition is tested. This means that whether the condition is true or false, the loop will execute at least once. An example of exit-controlled loops is a do-while loop.

Let's look at the examples of these types of loops in more details:

:- While Loop

The while loop has the following syntax:

while (condition) {
    // code to be executed
}

While "condition" is true, the block of code in the loop will be executed. Let's look at an example:

let myArray = [];
let i = 0;

while (i < 5) {
    myArray.push(i);
    i++;
}

console.log(myArray);

// output: [0, 1, 2, 3, 4]

In the code above, during each iteration, the while loop checks if the value of i is less than 5, it then pushes the value into myArray, and then increments it. Once the value is equal to or greater than 5, the loop stops running.

:- Do/While Loop

This loop is closely related to the while loop, it's only difference is that it checks for the condition after executing the code in the loop at least once.

do {
    // code to be executed
} while (condition)

Let's see the do/while loop in action using the example from the while loop earlier:

let myArray = [];
let i = 0;

do {
    myArray.push(i);
    i++;
} while (i < 5);

console.log(myArray);

// output: [0, 1, 2, 3, 4]

In most cases, the output using the while loop, and the do/while loop could look the same, but the difference starts to get clearer when we write a code in which the condition evaluates to false at the first iteration. Let's look at an example:

// In a while loop

let myArray = [];
let i = 6;

while (i < 5) {
    myArray.push(i);
    i++;
}

console.log(myArray);

/* 
The output of this code will be an empty array []
because "i" starts with 6 initially so the condition (i < 5) is false
*/
// In a do/while loop

let myArray = [];
let i = 6;

 do {
    myArray.push(i);
    i++;
} while (i < 5)

console.log(myArray);

/* 
The output of this code will be [6]
This is because "i" starts with 6 initially, and the do statement
will push 6 into the array, 
and then since the condition (i < 5) is false, the loop
will stop running.
*/

:- For Loop

The for loop has the following syntax:

for (initialization; condition; final_expression) {
    // code to be executed
    }

"initialization" is the area where you create the variable to be used in the loop. It runs first before the loop is executed. Once the loop has finished its execution, the variable is destroyed.

"condition" is the area where you write the expression that is to be checked before each iteration of the loop. It defines the condition for executing the code block in the loop. If the condition evaluates to true, the code in the loop is executed. If the condition evaluates to false, the loop stops.
By default, if the condition is omitted, it evaluates to true.

"final_expression" is the area where you write the expression that is to be checked after each iteration of the loop. It is executed after the code block has been executed. It is usually used to increment a counter but it can also be used to decrement a counter.

Example: We are going to write a code that will add numbers to an array, and keep writing until it reaches a limit.

// Create a variable with an empty array
let myArray = [];

// Create the variable that will be initialized and scoped into the loop
let i;

// Write the for loop
for (i = 0; i < 5; i++) {
        myArray.push(i);
    };

// Display the output of the code in the console
console.log(myArray);

Here, the instruction we have given to the loop is to check the variable i, and as long as its value is less than 5, it should place the value in myArray, and then increment it and check again.
By the time i < 5 evaluates to false, this 👇 is the output we would get in our console:

[0, 1, 2, 3, 4]


JavaScript also supports two other variations of the for loop. They are for/in loop and for/of loop.

:- For/in Loop

The for/in statement loops the properties of an object. It's syntax is

for (variableName in Object) {
        // code to be executed
    };

What it does is: in each iteration, one property of the "Object" is assigned to the variable named "variableName", and this continues until all the properties in "Object" has been processed.

Let's look at an example. Say we were asked to create an object listing 10 cities in Nigeria, and then to assign the properties of that object to a different variable, and then display it in our console. This is how our code would look:

// Create an object
nigerianCities = { 
        a : "Lagos",
        b : "Abuja",
        c : "Ibadan",
        d : "Port-Harcourt",
        e : "Kano",
        f : "Benin City",
        g : "Jos",
        h : "Calabar",
        i : "Ilorin",
        j : "Aba" 
};

// Create the variables to be used
let cityList = "";
let key;

// Write the loop to iterate over the properties
for (key in nigerianCities) {
    cityList += `${key} : ${nigerianCities[key]}; `;
};

// Display in the console
console.log(cityList);

And its output in the console will be

a : Lagos; b : Abuja; c : Ibadan; d : Port-Harcourt; e : Kano; 
f : Benin City; g : Jos; h : Calabar; i : Ilorin; j : Aba;

:- For/of Loop

The for/of statement loops over objects or data structures that are iterable, such as Arrays, Maps, Strings etc. Its syntax is:

for (variableName of Object) {
    // code to be executed
    }

Let's look at some examples.
Looping through an Array 👇

let houses = ["Duplex", "Apartment", "Bungalow", "Condo", "Penthouse"];
let x;

for (x of houses) {
    console.log(x);
    }

/* output:
Duplex
Apartment
Bungalow
Condo
Penthouse
*/

Looping through a string 👇

let text = "Hashnode";
let x;

for (x of text) {
  console.log(x);
}

/* output:
H
a
s
h
n
o
d
e
*/

Final words

Thanks for reading this far and making it to the end of this article 🤗. There's one more about loops to be aware of:
When writing loops, be careful not to write infinite loops (i.e.: loops that have no limits, and therefore could keep running forever) as these could overload and crash your browser or server.
In practice, browsers often provide ways to stop such loops, and in server-side JavaScript, you can kill the process. To be on the safe side though, write your loops carefully and check it properly before running it.

Thanks again for reading.


Credits:
Cover photo by Isabella and Louisa Fischer on Unsplash
JavaScript logo from freepnglogos.com

Further Reading:
FreeCodeCamp - JavaScript Loops Explained
Geeks for Geeks - Loops in JavaScript
W3Schools - For Loops, While & Do-While Loops
JavaScript Info - Loops: while and for

Comments (4)

Dinys Monvoisin's photo

You have cover do/while loop, do you usually use it?

Show +1 replies
Dinys Monvoisin's photo

That brings me to my next point. Was it worth it mentioning it in the article?

Divine Philip's photo

Dinys Monvoisin yes it was. The do/while loop, even though it's not used very frequently, is still a loop. It exists, and it works when it is used. So that's I felt it would be good to mention it as well.