JavaScript while
and do...while
In JavaScript, loops are a core concept for repeating code. While the for loop
is often used for a known number of iterations, the while
loop and do...while
loop are powerful tools when the number of iterations is determined by a condition rather than a fixed count. Both loops execute a block of code as long as a specified condition remains true. However, there are key differences in how they evaluate the condition.
while
Loop in JavaScript?A while
loop executes a block of code as long as a specified condition evaluates to true
. The condition is checked before each iteration, meaning the loop may not run at all if the condition is false initially.
while
Loop:
while (condition) {
// Code to be executed as long as the condition is true
}
while
Loop
let i = 0;
while (i < 5) {
console.log("Iteration number: " + i);
i++; // Incrementing the counter
}
Explanation:
i
is less than 5.i < 5
) is evaluated before each iteration.i
is incremented inside the loop, ensuring the loop progresses towards termination.
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
do...while
Loop in JavaScript?The do...while
loop is similar to the while
loop, but with a key difference: the condition is evaluated after each iteration. This guarantees that the code inside the loop is executed at least once, even if the condition is false from the start.
do...while
Loop:
do {
// Code to be executed
} while (condition);
do...while
Loop
let i = 0;
do {
console.log("Iteration number: " + i);
i++; // Incrementing the counter
} while (i < 5);
Explanation:
i < 5
).i
is incremented after each iteration.
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
while
and do...while
LoopsAlthough both loops are used for iteration, they have distinct behavior due to the timing of the condition check.
Aspect | while Loop |
do...while Loop |
---|---|---|
Condition Check | Condition is checked before each iteration. | Condition is checked after each iteration. |
Execution Guarantee | Code may not execute if the condition is false initially. | Code always executes at least once, even if the condition is false. |
Usage | Ideal when you are not sure how many iterations are needed, and the condition should be checked first. | Useful when the loop should run at least once, regardless of the condition. |
while
and do...while
Loopswhile
Loop for User Input ValidationImagine you want to repeatedly ask the user for input until they provide a valid response. This is a perfect scenario for a while
loop.
let userInput = "";
while (userInput !== "yes") {
userInput = prompt("Do you want to continue? (yes/no)");
}
console.log("User agreed to continue!");
Explanation:
"yes"
.do...while
Loop for Menu OptionsA do...while
loop can be handy when displaying a menu and prompting users for their selection at least once.
let userChoice;
do {
userChoice = prompt("Choose an option:\n1. Option A\n2. Option B\n3. Exit");
switch(userChoice) {
case "1":
console.log("You chose Option A");
break;
case "2":
console.log("You chose Option B");
break;
case "3":
console.log("Exiting...");
break;
default:
console.log("Invalid choice, please try again.");
}
} while (userChoice !== "3");
Explanation:
do...while
loop ensures the user sees the menu and is prompted at least once."Exit"
option.while
and do...while
LoopsYou can also nest a while
or do...while
loop inside another loop to handle more complex scenarios, such as working with multi-dimensional arrays or more intricate conditions.
while
Loop
let i = 1;
while (i <= 3) {
let j = 1;
while (j <= 3) {
console.log("i = " + i + ", j = " + j);
j++;
}
i++;
}
Explanation:
while
loop runs for i = 1
to i = 3
.while
loop runs for j = 1
to j = 3
for each iteration of the outer loop.
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Both the while
loop and the do...while
loop are important tools in JavaScript for repeating tasks under certain conditions. Understanding their differences and appropriate use cases will help you choose the right loop for your specific task.
Here’s a recap of the key points:
while
loop evaluates the condition before each iteration, which means the code inside the loop may not execute if the condition is false initially.do...while
loop guarantees that the code runs at least once, checking the condition only after each iteration.By mastering both loops, you will be able to efficiently handle repetitive tasks in JavaScript.