The while
and do-while
loops are control structures in JavaScript that allow you to repeat the 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 while 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 block of code 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, since the counter < 5
condition is evaluated as true
during the first five iterations.
do-while
Loop
The do-while
loop is similar to the while
loop, but it ensures that the block of code is executed at least once, even if the condition is false
from the beginning. The basic syntax is as follows:
do {
// Code to execute at least once
} while (condition);
The block of code 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 in 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 block of code, while thewhile
loop may not execute the block if the condition isfalse
from the beginning.
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 as long as the value of counter
is less than or equal to 10. In each iteration, the current value of counter
is printed and then 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 (negative number to finish): "));
while (number >= 0) {
sum += number; // Add the entered number to the 'sum' variable
number = parseInt(prompt("Enter another positive number (negative number to finish): "));
}
console.log(`The total sum of the 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 target = 7;
let index = 0;
let found = false;
while (index < numbers.length && !found) {
if (numbers[index] === target) {
found = true; // Marks that the number has been found
console.log(`Number ${target} found at position ${index}`);
}
index++; // Increment the index
}
if (!found) {
console.log(`Number ${target} not found in the list`);
}
This while
loop runs as long as the target 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 is indicated that it 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 prompts the user to enter “y” or “n” to confirm if they want to continue. The block of code is executed at least once and then repeated while the user does not enter a valid response.
These examples are intended to show how to use the while
and do-while
loops. It does not mean that it is the best way to solve the problems they address.