while loop in JavaScript with examples

Are you tired of writing code that executes repeatedly until a certain condition is met? Look no further because the JavaScript "while" loop is here to save the day! The while loop is a must-know tool for any aspiring JavaScript developer due to its simple syntax and powerful functionality.

The while loop in JavaScript is used to continue executing some blocks of code until the given condition evaluates to be false.

JavaScript while loop syntax

The syntax of the while loop in JavaScript is:

while(condition) {
   // body of the loop

Whatever block of code is written as the body of the loop, it will continue its execution again and again until the specified "condition" evaluates to false.

Note: Do not forget to update the loop variable. Otherwise, the loop may go for infinite execution.

JavaScript while loop example

Consider the following code as an example demonstrating the use of the "while" loop in the JavaScript language:

HTML with JavaScript Code
<!DOCTYPE html>
      let num = 5, i = 1;

The snapshot given below shows the sample output produced by the above JavaScript example:

while loop example in javascript

The dry run of the following JavaScript code from the above example is:

let num = 5, i = 1;

goes like this:

  1. Using the first statement, the value 5 will be initialized to num, and 1 will be initialized to i.
  2. Therefore num=5 and i=1.
  3. Now the condition of the while loop will be executed. That is, i<=10 or 1<=10 evaluates to true. Therefore, program flow goes inside the loop.
  4. And the value of num*i, that is, 5*1 or 5 will be printed on the console using the console.log() statement.
  5. Now the value of i will be incremented by 1 using the last statement. So i=2 now.
  6. Continue the same process from step no. 3 to step no. 5. This process continues until the condition of the while loop evaluates to false.

Before closing the discussion on the "while" loop, I'm willing to include one more example similar to the previous one, but I'm going to use proper comments to explain the code.

JavaScript Code
// Set a starting value for the counter variable
let counter = 1;

// While the counter is less than or equal to 5
while (counter <= 5) {
  // Print the value of the counter
  // Increment the counter by 1

Advantages of the "while" loop in JavaScript

Disadvantages of the "while" loop in JavaScript

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this article? Share it!

Like/follow us on social media for updates!