In this post, we will explore how to use while loops and do-while loops in JavaScript with some practical examples.
While loop
The while
loop runs as long as a specified condition is true. Let's look at an example:
let index = 0;
while (index <= 10) {
console.log(`value of index is ${index}`);
index += 2; //it also means index = index + 2
//index = index + 2; // another way of writing index +=2
}
//output
value of index is 0
value of index is 2
value of index is 4
value of index is 6
value of index is 8
value of index is 10
In this example, the loop will print the value of index
as long as it is less than or equal to 10. The value of index
is incremented by 2 in each iteration.
Looping Through an Array with While Loop
We can also use a while
loop to iterate through an array:
let myArray = ["flash", "batman", "superman"];
let arr = 0;
while (arr < myArray.length) {
console.log(`value is ${myArray[arr]}`);
arr += 1; //arr = arr + 1;
}
//output:
//value is flash
//value is batman
//value is superman
Here, we loop through the array myArray
and print each value. The loop continues until arr
is less than the length of the array.
Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the loop body will be executed at least once. This is because the condition is checked after the loop body is executed. Let's see an example:
let score = 1;
do {
console.log(`score is ${score}`);
score++;
} while (score <= 10);
//output:
score is 1
score is 2
score is 3
score is 4
score is 5
score is 6
score is 7
score is 8
score is 9
score is 10
In this example, the value of score
will be printed, and then score
will be incremented. This continues until score
is greater than 10.
Example with Initial Condition Not Met
Even if the initial condition is not met, the do-while
loop will execute the body at least once:
let number = 11;
do {
console.log(`number is ${number}`); // it will print number once and after checking condition, it will come out of the loop
number++;
} while (number <= 10);
In this case, number
is 11, which is greater than 10, but the loop body will still execute once before the condition is checked.
Conclusion
Both while
and do-while
loops are essential for repeating tasks in JavaScript. While while
loops check the condition before the loop body executes, do-while
loops check the condition after the loop body executes, ensuring that the body runs at least once.
Understanding these loops helps in efficiently handling repetitive tasks and can make your code more readable and concise.