JavaScript while and do-while loops Tutorial

What is a while Loop?

  1. The JavaScript "while" statement makes a loop that runs a block of code as long as a certain condition stays true.
  2. It's handy when you need to keep running a piece of code until a specific condition is no longer true.
  3. Let's see how while loop works
  4. The "while" statement checks the expression before every loop iteration.
  5. If the expression is true, the "while" statement runs the code inside it curly braces. If it's false, the loop ends.
  6. This type of loop is called a pretest loop as it checks the expression before each iteration.
  7. If the expression is false from the start, the "while" loop won't run at all.
  8. Imagine you are developing a temperature monitoring system, and you want to continuously read and display the current temperature until a certain threshold is reached. This is where while loops comes in.

Syntax:

while (condition/truthy or falsy value) {
    // code block to run
    update;
}

Example

let count = 1;
while (count <= 5) {
    console.log("Count: " + count);
    count++;
}

The output of the above code will be

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
    

In this example, the loop continues executing as long as the count variable is less than or equal to 5. It increments count by 1 in each iteration.

let chargePercent = 90;
while (chargePercent <= 100){
    console.log(`${chargePercent} %`);
    chargePercent++;
}

The output of the above code will be

90 %
91 %
92 %
93 %
94 %
95 %
96 %
97 %
98 %
99 %
100 %

The program initializes a variable chargePercent with an initial value of 90.

The while loop is used to iterate as long as the condition chargePercent <= 100 is true.

Inside the loop, It logs the current value of chargePercent to the console using console.log(), indicating the battery charge percentage. .

The chargePercent is then incremented by 1 with the chargePercent++ statement.

The loop continues to run until chargePercent is no longer less than or equal to 100.

When you run this program, it will output the battery charge percentage from 90% to 100% in the console. The loop increments the charge percentage in each iteration and stops when it reaches or exceeds 100%.

Infinite while Loop

  1. We mentioned that the while loop keeps running the code as long as the condition remains true.
  2. This means that the loop can repeat itself multiple times if the condition stays true throughout.
while(true){
    console.log("This loop always executes, To stop this you might turn off the computer close the editor");    
}

let number = 9;
while(number == 9){
    console.log("This loop always executes");
}

The first while loop with while (true) creates an infinite loop, as the condition is always true. It continuously logs the specified message to the console. To stop this loop, you would need to interrupt the execution, for example, by manually stopping the program, closing the editor, or turning off the computer.

The second while loop with while (number == 9) also creates an infinite loop, given that the initial value of number is set to 9 and the condition remains true. It will repeatedly log the specified message to the console. To stop this loop, you would need to change the value of number or introduce a condition inside the loop that eventually evaluates to false.

while Loop to Iterate Through an Array

  1. while loops are not just for counting; they can also be used to iterate through arrays. In this example, we'll iterate through an array of fruits and print each one.
const fruits = ["apple", "banana", "cherry", "date"];
let i = 0;

while (i < fruits.length) {
    console.log("Fruit: " + fruits[i]);
    i++;
}

/* Output: 
Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date
*/
    

The i variable is used as an index to access elements of the fruits array, and the loop continues as long as i is less than the length of the array.

Controlling while Loops with Break and Continue

  1. In some cases, you may want to exit a while loop prematurely or skip a specific iteration. You can do this using the break and continue statements.

Break

Exits the loop before it actually exits.

let count = 1;
while (count <= 5) {
    if (count === 3) {
        break; // Exit the loop when count is 3
    }
    console.log("Count: " + count);
    count++;
}
/* Output
Count: 1
Count: 2
*/
    

continue

Skips the current iteration and proceeds to the next one.

let count = 1;
while (count <= 5) {
    if (count === 3) {
        count++;
        continue; // Skip iteration when count is 3
    }
    console.log("Count: " + count);
    count++;
}
Count: 1
Count: 2
Count: 4
Count: 5

What is a do...while Loop?

  1. A do...whilee loop is a control flow statement in JavaScript that executes a block of code at least once, and then repeatedly as long as a specified condition remains true.
  2. Unlike the while loop, which checks the condition before the first iteration, the do...whilee loop guarantees at least one execution of the code.

Syntax

do {
    // Code to be executed
} while (condition);

Example:

let count = 1;
do {
    console.log("Count: " + count);
    count++;
} while (count <= 5);

/* Output: 
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/
    
do {
    console.log("This will executes once even though condition is false.")
}
while(false);

// Output: This will executes once even though condition is false.

Logging In with User Validation

do-while

  1. In a web application, you want to prompt the user to log in with their username and password. You need to ensure that the user provides valid input before proceeding.
let validLogin = false;
do {
    let username = prompt("Enter your username:");
    let password = prompt("Enter your password:");

    // Perform authentication logic
    if (username === "user123" && password === "pass123") {
        console.log("Login successful!");
        validLogin = true;
    } else {
        console.log("Invalid login credentials. Please try again.");
    }
} while (!validLogin);
    

In this do...while loop example, the user is repeatedly prompted to log in until they provide valid credentials. The loop guarantees that the login prompt is shown at least once.

while

let validLogin = false;
while (!validLogin) {
    let username = prompt("Enter your username:");
    let password = prompt("Enter your password:");

    // Perform authentication logic
    if (username === "user123" && password === "pass123") {
        console.log("Login successful!");
        validLogin = true;
    } else {
        console.log("Invalid login credentials. Please try again.");
    }
}
    

In this while loop example, the user is also prompted to log in until they provide valid credentials.

However, there's no guarantee that the login prompt will be shown at least once. If validLogin is already true initially, the loop will not execute, which might not be ideal for a login scenario.

When to use while loops

  1. Iterating Over Arrays
  2. User Input Validation
  3. Processing Data Until a Condition is Met
  4. File or Data Reading
  5. Asynchronous Operations
  6. Infinite Loops with Exit Conditions