JavaScript while and do-while loops Tutorial
What is a while Loop?
- The JavaScript "while" statement makes a loop that runs a block of code as long as a certain condition stays true.
- It's handy when you need to keep running a piece of code until a specific condition is no longer true.
- Let's see how while loop works
- The "while" statement checks the expression before every loop iteration.
- If the expression is true, the "while" statement runs the code inside it curly braces. If it's false, the loop ends.
- This type of loop is called a pretest loop as it checks the expression before each iteration.
- If the expression is false from the start, the "while" loop won't run at all.
- 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
- We mentioned that the while loop keeps running the code as long as the condition remains true.
- 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
- 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
- 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?
- 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.
- 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
- 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
- Iterating Over Arrays
- User Input Validation
- Processing Data Until a Condition is Met
- File or Data Reading
- Asynchronous Operations
- Infinite Loops with Exit Conditions