While Loop in JavaScript

The while loop in JavaScript is the most fundamental loop statement that repeats a statement or series of statements as long as the specified conditional expression evaluates to true.

In other words, a while loop repeats the body of the loop as long as the loop condition holds. Each repetition of the body of loop is called iteration.

JavaScript while loop is the simplest of all the looping structures. It is an entry-controlled loop statement. In the entry-controlled loop, the test condition evaluates first. If the specified condition is true, then the body of loop executes.

If the condition does not satisfy, then the body of loop does not execute. Thus, the while loop executes a block of statements repeatedly as long as the test condition is true.

Syntax of While Loop in JavaScript


The general syntax for using the while loop in JavaScript is as follows:

Initialization;
while (test condition)
{
  // Loop body
     statement(s);
}

In the above syntax, the while is a keyword. The test condition may be a comparison or logical expression (i.e. an expression that returns true or false) that controls the execution of body loop.

We place test condition between the set of parentheses that follow the while keyword. Statements are a block of statements that will execute each time through the loop.

The part of the loop that contains statements to be executed repeatedly is called the loop body. A loop body may contain one or more statements.

Curly braces need only if the loop body has two or more statements. However, it is good programming practice to use curly braces even if the loop body contains only one statement.

How does While Loop Work?


Let’s understand how a while loop works in JavaScript:

1. Evaluates the test condition or expression in the while() statement.

2. When the test condition is true, then the body of loop (i.e. a block of statements) executes. After the execution of loop body, the test condition once again evaluates to true.

3. If the specified condition is true, the loop body executes once again. This process of repeated execution of loop body continues by JavaScript interpreter until the conditional expression finally becomes false.

4. Once the conditional expression is false, the loop ends and the control of execution transfers out of the loop.

5. On exit, the program continues with the next statement immediately after closing curly braces of while loop. Each execution of the loop body refers to as an iteration (or repetition).

The flowchart for while loop in JavaScript has shown in the below diagram.

JavaScript while loop flowchart diagram


Now consider the following code segment below:

// Initialization. This variable has defined outside the loop and will update inside the loop.
  let count = 0;
// Declare while loop statement.
// Loop continuation conditional expression that must always appear inside the parentheses. 
  while (count < 10) 
  {
 // Body of the loop.
    document.write("Hello world"); // This statement will execute while the condition is true.
    count++; // It counts the number of executions, and increments count by 1.
  }
  statements; // continue program if the condition is false.

From the above example, let’s understand how the while loop actually works. The flowchart for this code segment has shown in the above diagram.

In this example code, the body of loop will execute 10 times for count = 0, 1, 2, 3, . . . . . , 9. Each time a statement “Hello world” will print on the browser.

When the count is equal to 10, the condition will be false and the loop will end. The control of execution will transfer out of the loop to execute the rest of code inside the program.

In the above example, count is a control variable that controls the number of executions. It increments by 1 after each loop. This kind of loop is called counter-controlled loop.

Examples based on JavaScript While loop statement


Example 1: Let’s create a simple JavaScript program to display the numbers from 1 to 5 by using while loop statement.

<script>
let i = 1; // Initialization.
while(i <= 5)
{
   document.write(i, "<br/>");
   i++; // Increment.
}
</script>
Output:
     1
     2
     3
     4
     5

Example 2: Let’s create a simple JavaScript program to print a “Hello World!” four times on the web browser using a while loop.

<script>
let i = 1; // Initialization.
while(i < 5)
{
  document.write("Hello World!", "<br/>");
  i++; // Increment.
}
</script>
Output:
     Hello World!
     Hello World!
     Hello World!
     Hello World!

Example 3: Let’s make a JavaScript program to display numbers from 5 to 1 by using while loop statement.

<script>
let i = 5;
while(i >= 1)
{
  document.write(i, "<br/>");
  i--; // decrement.
}
</script>
Output:
      5
      4
      3
      2
      1

Example 4: Let’s take a simple example program where we will add the number from 1 to 10 using while loop and display the sum on the browser.

<script>
  let sum = 0, i = 1;
  while (i <= 10)
  {
    sum = sum + i;
    i++;
  }
  document.write("Sum is " + sum); // sum is 55
</script>
Output:
        Sum is 55

In the preceding example program, the variable i is initially set to 1 and the sum initially set to 0. When the conditional expression (i <= 10) is true, the program adds i to the sum. Then, the variable i incremented to 2.

Again, the conditional expression will evaluate to true. If it is true, the program again adds i to sum. The variable once again incremented to 3.

This process continues up to 10. Each time the program adds i to sum if the condition is true. After 10th iterations, the control of execution exits the loop. Therefore, the sum is 1 + 2 + 3 +… + 10 = 55.


Note: If the conditional expression is always true, then you will never exist the while loop. So, be very careful while using while loops in the program.

While loop without Loop Body Example Program


Example 5: Consider another example program where the body of while loop will be empty. We will calculate the mid-value between “x” and “y” where “x” is equal to 10 and “y” is equal to 20.

<script>
  let x = 10, y = 20;
  while (++x < --y); // No body in this loop.
  document.write("Mid value is " + x);
</script>
Output:
      Mid value is 15

The preceding example program determines the mid-value between x and y. Let’s understand how the while loop in this program works.

a) Initially, the value of x set to 10 and y set to 20. These initially set values compare with one another. If the value of x is less than the value of y, the loop repeats.

b) Now, the value of x has incremented by 1, and the value of y decrement’d by 1. These new values again compare with one another. If the new value of x is still less than the new value of y, the loop once again repeats.

c) This process continues until the value of x is equal to or greater than the value of y.

d) When the value of x is equal to or greater than the value of y, the loop stops.

e) Upon exit from the loop, the variable x will hold a value that is midway between the original values of x and y.

As you can see in this example program, there is no need for a loop body. All the action happens within the conditional expression itself.


Example 6: Consider an example program in which we will display numbers between 5 and 10 using while loop statement.

<script>
  let x = 5;
  while ((x >= 5) && (x < 10))
  {
    document.write("Value of x: " + x, "<br>");
    x++;
  }
</script>
Output:
     Value of x: 5
     Value of x: 6
     Value of x: 7
     Value of x: 8
     Value of x: 9

In this tutorial, you learned while loop statement in JavaScript with various example programs. I hope that you will have understood the basic syntax and working of while loop statement.
Thanks for reading!!!