The while
and do-while
loops are control structures in JavaScript that allow the repeated execution of a block of code while a specific condition is met.
Unlike the for
loop, which is used when the exact number of iterations is known, the while
and do-while
loops are ideal when the number of iterations is unknown or depends on an exit condition.
If you want to learn more about Loops
check out the Introduction to Programming Course read more
while
Loop
The while
loop repeats a block of code as long as a given condition is true
. The basic syntax of a while
loop in JavaScript is as follows:
while (condition) {
// Code to execute while the condition is true
}
The code block is executed repeatedly as long as the specified condition is true
. It is important to be careful with the condition to avoid infinite loops.
Basic Example
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}
In this example, the while
loop will print the numbers from 0 to 4, as the condition counter < 5
evaluates to true
during the first five iterations.
do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block will execute at least once, even if the condition is false
from the start. The basic syntax is as follows:
do {
// Code to execute at least once
} while (condition);
The code block is executed first, and then the condition is checked. If the condition is true
, the block is executed again; if it is false
, the loop ends.
Basic Example
let counter = 0;
do {
console.log(counter);
counter++;
} while (counter < 5);
This do-while
loop will produce the same output as the while
loop from the previous example.
Differences between while
and do-while
- The
while
loop checks the condition before each iteration, while thedo-while
loop checks the condition after each iteration. - The
do-while
loop guarantees at least one execution of the code block, while thewhile
loop may not execute the block if the condition isfalse
from the start.
Practical Examples
Counting to 10
In this example, a while
loop is used to count from 1 to 10 and print each number.
let counter = 1;
while (counter <= 10) {
console.log(counter);
counter++; // Increment the counter by 1
}
This while
loop runs while the value of counter
is less than or equal to 10. In each iteration, the current value of counter
is printed, and then it is incremented by 1.
Summing Positive Numbers Entered by the User
In this example, a while
loop is used to sum positive numbers entered by the user until a negative number is entered.
let sum = 0;
let number;
number = parseInt(prompt("Enter a positive number (a negative number to finish): "));
while (number >= 0) {
sum += number; // Adds the entered number to the 'sum' variable
number = parseInt(prompt("Enter another positive number (a negative number to finish): "));
}
console.log(`The total sum of positive numbers is: ${sum}`);
This while
loop runs as long as the user enters positive numbers. Each number is added to the sum
variable. The loop ends when a negative number is entered.
Searching for a Number in a List
In this example, a while
loop is used to search for a specific number in a list of numbers.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let searched = 7;
let index = 0;
let found = false;
while (index < numbers.length && !found) {
if (numbers[index] === searched) {
found = true; // Marks that the number has been found
console.log(`Number ${searched} found at position ${index}`);
}
index++; // Increment the index
}
if (!found) {
console.log(`Number ${searched} not found in the list`);
}
This while
loop runs as long as the searched number has not been found and the index is within the range of the list.
If the number is found, it is marked as found and its position is printed. If the loop ends without finding the number, it indicates that the number was not found in the list.
User Input Validation
In this example, a do-while
loop is used to prompt the user to enter “y” or “n” to confirm if they want to continue.
let response;
do {
response = prompt("Do you want to continue? (y/n): ").toLowerCase();
} while (response !== "y" && response !== "n");
console.log("Program finished.");
This do-while
loop asks the user to enter “y” or “n” to confirm if they want to continue. The code block executes at least once and then repeats while the user does not enter a valid response.
These examples are intended to show how to use while
and do-while
loops. It does not mean that it is the best way to solve the problems they address.