JavaScript

JavaScript Loops – A Guide for Absolute Beginners

In computing, almost all programming languages support the idea of loops. In computing, loops are a set of instructions that allow the programmer to do something repeatedly in a quick and efficient manner. Loops iterate/repeatedly execute through a block of code until a certain condition is met.

All high-level programming languages provide several different types of loops. The syntax of these loops may be different but they are used to perform the same tasks. These loops are interchangeable but some are specifically built to be used in some specific conditions.

The most popular loops present in most programming languages are for and while loops; here we will discuss them along with their extensions which are present in JavaScript:

How to use the for loop in JavaScript

The most simplest and commonly used loop in JavaScript is the for loop; for loops are preferred over other loops when the programmer knows the definite number of times the loop is going to run.

Let’s take a look at the syntax of the for loop to understand why:

for ( initialization ; condition ; variable modification ) {
  // code statements to be executed
}

The for loop takes three arguments, initialization, condition and variable modification:

  • The first argument i.e. initialization runs only one time before the execution of the loop; It initializes a variable which is used in the condition for the loop.
  • The second argument i.e. condition is evaluated before every iteration; the loop terminates when this condition is satisfied.
  • The third and the last argument variable modification is used to modify the value of the variable used in condition after every iteration of the loop.

The arguments of the for loops specify the definite number of iterations it is going to run. They specify the starting point (initialization) and the ending point (condition) of the loop. Although all of the arguments are optional (the for loop will run even if you do not specify the condition) however it is not recommended to leave the condition argument empty as it will create an infinite loop which can crash your browser.

Now let’s try an example to better understand for loop:

Note: The browser console is used for the demonstration of examples in this article.

In this example we will count down from 10 to 1 using a for loop:

for (let index = 10; index >= 1; index--) {
    console.log(index);
}

In the above example:

  • Index is initialized to 10
  • Then the condition is checked, since the index is greater than or equal to 1 condition is true the loop is executed and the value of index is printed to the console
  • After the first iteration the index variable is decremented by one. The operator reduces the value of the index by one.
  • Then the condition is again checked; As the condition is still true the loop is again executed.

This process keeps recurring as long as the condition for the loop remains true. When the value of the index recheas 0, the condition greater than or equal to 1 is no longer true and the loop terminates.

We can perform any operation on the variable in the last argument of the for loop statement:

for (let index = 2; index < 500; index*=2) {
    console.log(index);
}

How to use while loop in JavaScript

While loops only take one argument which is the condition for the loop:

They are mostly used when the code has to run an unknown number of times until the condition is satisfied:

while (condition) {
  // Statements
}

Let’s take a look at an example where we will generate a random number by using the Math.random() method inside the loop; The loop will keep running until the Math.random() method produces an odd number:

runLoopAgain = true;

while (runLoopAgain) {
    num = Math.random().toFixed(1)*10;
    if (num % 2 != 0) {
        runLoopAgain = false;
    }
    console.log(num);
}

In the above example we first declared a boolean named runLoopAgain and assigned it a value i.e true. The while loop evaluates the condition before the execution of the loop; as the variable runLoopAgain is the condition of the loop and is true the while loop is executed. Inside the body of the while loop we have used the random method of the Math object along with the .toFixed method to get a random number between zero and nine. Then we have used a conditional statement to check if the number is divisible by two (to check if it is even or odd). If the number is odd then the runLoopAgain variable will become false and the loop will terminate otherwise the variable/condition will remain true and the loop will keep running.

The tasks that we performed in the above examples using the for loop can also be performed with while loop:

let i = 10;

while (i >= 1) {
    console.log(i);
    i--;
}

let i = 2;

while (i < 500) {
    console.log(i);
    i*=2;
}

How to use the break statement in While loop

The break statements can be used inside the loop’s body to terminate the loop. Let’s look at an example:

let i = 2;
while (i < 20) {
    if (i % 5 == 0) {
        break;
    }
    console.log(i);
    i+=2;
}

In this example I have used a while loop to print out every even number which is less than 21 but I am only getting even numbers less than 9; why is that? This is because I have used a break statement which terminates the loop if the even number is a multiple of 5. We can use the break statement to have different conditions for the termination of a while loop inside the loop’s body:

How to use the continue statement in While loop

The continue statement is used to skip an iteration and move onto the next of the while loop. For instance, if we want to skip the number which is a multiple of 5 instead of just terminating the loop in the above example then we will use the continue statement:

let i = 2;
while (i < 21) {
    if (i % 5 == 0) {
        i+=2;
        continue;
    }
    console.log(i);
    i+=2;
}

As you can see that 5, 10 and 20 are missing because they are multiples of 5 as well as being even numbers.

How to use the do while loop in JavaScript

The do while loop is built on top of the while loop meaning it is an extension of the while loop.

In while loop the condition is evaluated before the execution of the loop’s body whereas the do while loop does the opposite and checks it after the execution of the body of the loop.

runLoopAgain = true;

while (runLoopAgain) {
    num = Math.random().toFixed(1)*10;
    if (num % 2 != 0) {
        runLoopAgain = false;
    }
    console.log(num);
}

In this example given above we had to declare and initialize the runLoopAgain variable before the body of the loop because the while loop evaluates the condition before the iteration.

The do while loop checks the condition after every iteration, so If we are sure that we want to run the code present inside the loop at least one time then we use the do while loop. As we are sure in this example that we have to at least generate one random number before we check whether it is even or odd, a better way to write it would be:

do {
    num = Math.random().toFixed(1)*10;
    console.log(num);
} while (num % 2 == 0);

How to use the for in, for of and foreach loops in JavaScript

The for in, for of and foreach loops in JavaScript are an extension of the for loop. Here we will discuss all of them; The for in loop is used to iterate over the properties of an object. Each iteration of the for in loop returns a key which can be used to access the value of the key:

var employee = {firstName:"Mary", lastName:"Jane", age:33, id:092, department: "Education"};

for (let p in employee)
{
  console.log(p);
  console.log(employee[p]);
}

If the for in loop is applied to an array, it returns the index of each element. If we want to get the value present at each index then we can use the for of loop.

var num = [5, 6, 7, 8, 9];

for (let d of num)
{
  console.log(d);
}

The for of loop is used to loop through iterable objects such as arrays, Maps, strings etc. If we use the for of loop on a string then it returns one character of the string each iteration:

var greet = "Welcome to Linux Hint!";

for (let c of greet)
{
  console.log(c);
}

The .foreach() loop is used to perform a specific action on each element of the array; it loops through elements of the array and calls a function once for every element.

The .foreach() loop takes a callback function as an argument which further takes three arguments, two of which are optional; The only required argument is the value of the current element. The index of the element and the whole array itself can be given as arguments to the callback function as well. Now we will look at an example where we have used the .foreach() loop to multiply each element of the array by two and print it to the console:

var numbers= [99, 85, 788, 2, 255, 598];
numbers.forEach(function (value)
{
  console.log(value +" * 2 = " + value*2);
})

Conclusion

Loops are control flow statements which are used to reduce code inefficiency and write more concise code. They are one of the most fundamental part of any major high level programming language. In this post we learned all about loops in JavaScript; we used JavaScript syntax to learn about for and while loops along with their extensions. Moreover, the break and continue statement for while loops were also discussed.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.