Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript While Loop

The while loop is used to execute the same code repeatedly until the defined condition becomes true. For example, you have a text file that contains lines that you do not know the number of. You can work with a while loop and set the condition as long as we have not reached the end, read the lines. The while loop is similar to the for loop except that the for loop works with a known number of times while the while loop works with unknown number of execution times.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-while

Open the directory javascript-while in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • while.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-while
-while.js

Open the directory javascript-while in Visual Studio Code or your favorite code editor

While loop syntax

The syntax for the while loop is as follows

while (condition is true){
	//do something
}

HERE,

  • while (condition is true){...} the while keyword is used to start the while loop. The condition is enclosed in parenthesis and the code block to be executed is placed between the {...} curly brackets.

The code block for the while loop will be executed as long as the condition remains true. An infinity loop is a loop that executes continuously because the set condition is always true. You should always make sure that you include a mechanism that falsies your condition so that the program can exit the loop.

While loop example

Let's now look at a practical example. We will generate numbers from 1 to 10 using a while loop.

Open the file while.js and add the following code

let i = 1;

while (i < 11){
    console.log(i);
    i++;
}

HERE,

  • let i = 1; defines a variable i that is initialized to the value 1.
  • while (i < 11){...} defines a while loop that evaluates the condition i < 11. If the condition is true then the code within the loop is executed. If the condition is false then the code within the loop is not executed.
  • console.log(i); prints the value of the console to the terminal.
  • i++ increments the value of i. This is what causes the loop condition to evaluate to false when the count exceeds 10.

Open the terminal in Visual Studio Code

Run the following command

node while.js

You should be able to get the following results.

1
2
3
4
5
6
7
8
9
10

The while loop is only executed when the condition is true. However, you may have cases where you want to execute the loop at least once before you evaluate the condition. The do while loop does that and we will cover it in the next section.

Do while loop syntax

The do while loop is similar to the while loop except the code within the do block must be executed at least once before evaluating the condition. The syntax for the do loop is as follows

do {
	//do something
} while (condition is true);

HERE,

  • do {...} defines the do loop and the code block that must be executed for the loop.
  • while (condition is true); sets the condition that must be evaluated and resolve to true if the code within the loop is to be executed again.

Do while loop example

The following example prints numbers between 1 and 5 using a do while loop

let n = 0;

do {
    console.log(n);
    n++;
} while (n < 5);

HERE,

  • let n = 0; defines a variable n that is initialized to the value 0.
  • do{...} defines a do while loop that prints the value of n to the console then increments the value of n by 1.
  • } while (n < 5); defines the condition for the while loop. In our case, the loop should be executed as long as the value of n is less than 5.

Open the terminal then execute the following code

0
1
2
3
4

JavaScript While Loop Break statement

The break statement is used to terminate the loop execution prematurely. Calling the break statement within the while loop stops execution even if the set condition is true. Let's look at a practical example

let i = 1;

while (i < 11){
    if (i == 5){
        break;
    }
    
    console.log(i);
    i++;
}

HERE,

  • if (i == 5){...} checks if the value of i is 5. If the condition evaluates to true then we call the break; statement within the while loop

Executing the above code produces the following results

1
2
3
4

Notice we only generated numbers up to 4 despite the fact that we set the loop condition to count up to 10.

JavaScript While Loop Continue Statement

The continue statement is used to skip executing the code below the continue statement. For example, you might want to print out odd numbers from 1 to 9. You can use the continue statement to skip printing even numbers like so

let k = 0;

while (k < 10){
    k++;

    if (k % 2 == 0){
        continue;
    }

    console.log(k);
}

HERE,

  • let k = 0; defines a variable k that is initialized to 0.
  • while (k < 10){...} defines the while loop
  • k++; increments our condition variable k
  • if (k % 2 == 0){...} checks if the value of k is divisible by 2 without giving a remainder. If it is divisible by 2 then we are dealing with an even number so we skip to the next step. This is achieved by calling the continue statement.

Executing the above code produces the following results

1
3
5
7
9

Summary

While loops are used to execute the same piece of code when you are not sure how many times you want to execute the same code. The while loop has two variations while and do while. while loop is only executed if the set condition is true while do while is executed at least once before checking the condition and proceeding depending on the results. The break statement is used to terminate the loop prematurely. The continue statement is used to skip the execution of the code below the continue statement and reevaluate the condition again.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript For Loop

JavaScript Exception Handling

Leave A Reply