while Loop

Introduction

The while loop is a looping statement in JavaScript that repeatedly executes a block of code as long as a specified condition remains true.

Unlike the for loop, where the number of iterations is usually known in advance, the while loop is ideal when the number of iterations is unknown and depends on a condition that changes during program execution.

For automation engineers, the while loop is commonly used to wait for conditions, process dynamic data, handle pagination, retry failed operations, and poll APIs until the desired result is obtained.


What is a while Loop?

A while loop repeatedly executes a block of code until its condition becomes false.

Before each iteration, JavaScript checks the condition.

  • If the condition is true, the loop executes.

  • If the condition is false, the loop terminates.


Syntax

while (condition) {

    // Code to execute

}

Flow of Execution

Start
   │
   ▼
Check Condition
   │
 ┌─┴─────────────┐
 │               │
True          False
 │               │
 ▼               ▼
Execute Code    End
 │
 ▼
Update Variable
 │
 └──────────────► Repeat

Why Do We Use while Loops?

The while loop helps developers:

  • Execute code repeatedly based on a condition.

  • Handle situations where the number of iterations is unknown.

  • Process dynamic input.

  • Implement retry mechanisms.

  • Simplify repetitive operations.


Basic Example

let count = 1;

while (count <= 5) {

    console.log(count);

    count++;

}

Output

1
2
3
4
5

Printing Even Numbers

let number = 2;

while (number <= 10) {

    console.log(number);

    number += 2;

}

Output

2
4
6
8
10

Counting Backwards

let count = 5;

while (count >= 1) {

    console.log(count);

    count--;

}

Output

5
4
3
2
1

Calculating the Sum of Numbers

let number = 1;
let sum = 0;

while (number <= 5) {

    sum += number;

    number++;

}

console.log(sum);

Output

15

Iterating Through an Array

const fruits = ["Apple", "Banana", "Orange"];

let index = 0;

while (index < fruits.length) {

    console.log(fruits[index]);

    index++;

}

Output

Apple
Banana
Orange

Real-World Example

Suppose an ATM keeps asking for the correct PIN until the user enters it.

let enteredPin = 1111;
const correctPin = 1234;

while (enteredPin !== correctPin) {

    console.log("Incorrect PIN");

    enteredPin = 1234;

}

console.log("Access Granted");

Output

Incorrect PIN
Access Granted

Another example:

let stock = 3;

while (stock > 0) {

    console.log(`Remaining Stock: ${stock}`);

    stock--;

}

Output

Remaining Stock: 3
Remaining Stock: 2
Remaining Stock: 1

Automation Testing Example

Automation engineers frequently use while loops for retry logic and dynamic waiting.

Playwright Example

Wait until an element becomes visible.

let visible = false;

while (!visible) {

    visible = await page.locator("#loginButton").isVisible();

}

console.log("Login button is visible.");

Selenium Example

Retry until the page title matches the expected value.

let title = "";

while (title !== "Dashboard") {

    title = await driver.getTitle();

}

console.log("Dashboard Loaded");

API Testing Example

Retry an API request until it returns status code 200.

let statusCode = 500;

while (statusCode !== 200) {

    console.log("Retrying API Request...");

    statusCode = 200;

}

console.log("API Request Successful");

Output

Retrying API Request...
API Request Successful

Processing Test Data

const browsers = ["Chrome", "Firefox", "Edge"];

let index = 0;

while (index < browsers.length) {

    console.log(`Running tests on ${browsers[index]}`);

    index++;

}

Output

Running tests on Chrome
Running tests on Firefox
Running tests on Edge

Infinite while Loop

If the condition never becomes false, the loop runs forever.

while (true) {

    console.log("Running...");

}

This creates an infinite loop unless interrupted.


while vs for Loop

Using a for Loop

for (let i = 1; i <= 5; i++) {

    console.log(i);

}

Using a while Loop

let i = 1;

while (i <= 5) {

    console.log(i);

    i++;

}

Both loops produce the same output.

Use:

  • for → When the number of iterations is known.

  • while → When the number of iterations depends on a condition.


Common Mistakes

Forgetting to Update the Variable

Incorrect:

let count = 1;

while (count <= 5) {

    console.log(count);

}

This creates an infinite loop because count never changes.

Correct:

count++;

Incorrect Loop Condition

Incorrect:

let i = 10;

while (i < 5) {

    console.log(i);

}

The condition is false from the beginning, so the loop never executes.


Modifying the Wrong Variable

Always update the variable used in the loop condition.


Best Practices

Ensure the Condition Eventually Becomes False

Always update the loop variable to prevent infinite loops.


Keep Loop Logic Simple

Avoid placing too much business logic inside the loop body.


Use Meaningful Variable Names

Instead of:

let x = 0;

Use:

let retryCount = 0;

This makes the code easier to understand.


Use while Only When Appropriate

If the number of iterations is known, a for loop is often a better choice.


Conclusion

The while loop is a powerful looping construct that repeatedly executes code as long as a condition remains true. It is especially useful when the number of iterations cannot be determined beforehand, making it ideal for dynamic processes and condition-based execution.

For automation engineers, the while loop is widely used for retry mechanisms, waiting for UI elements, polling APIs, handling dynamic content, and processing data until a desired condition is met.


Frequently Asked Questions (FAQs)

What is a while loop in JavaScript?

A while loop repeatedly executes a block of code as long as its condition evaluates to true.


What is the syntax of a while loop?

while (condition) {

    // Code

}

When should I use a while loop?

Use a while loop when the number of iterations is unknown and depends on a condition.


What happens if the condition is initially false?

The loop does not execute even once.


Why is the while loop useful in automation testing?

Automation engineers use while loops for waiting until elements appear, retrying failed operations, polling APIs, processing dynamic data, and implementing condition-based execution.


Key Takeaways

  • A while loop executes code repeatedly while a condition is true.

  • The condition is checked before every iteration.

  • If the condition is initially false, the loop does not execute.

  • Always update the loop variable to avoid infinite loops.

  • while loops are ideal when the number of iterations is unknown.

  • They are commonly used for retries and waiting mechanisms.

  • Keep loop conditions simple and readable.

  • Use meaningful variable names.

  • while loops are widely used in web development and automation testing.

  • Mastering the while loop is essential before learning the do...while loop and advanced iteration techniques.