Mastering Java Script | DO WHILE Loop
Welcome back to our "Master JavaScript" course! Let's dive into another essential loop in JavaScript: the do...while
loop.
Before we begin, make sure you've checked out the videos on the for
, for...in
, and while
loops in the channel. Hit the subscribe button if you haven't already!
The do...while
loop is quite similar to the while
loop, with one crucial difference: it executes the code block at least once before checking the loop's condition. This means that the code block will run once, and then the loop will continue executing as long as the specified condition remains true.
Let's see how the do...while
loop works with an example:
1
2
3
4
5
6
let i = 0; // Initialization
do {
// Code to be executed for each iteration
console.log(i);
i++; // Increment
} while (i < 5); // Condition
In this example, we initialise the variable i
to 0. The do...while
loop will run the code block at least once, regardless of the condition. Inside the loop, we perform the desired operations, such as printing the value of i
, and then increment i
using i++
.
After the code block runs, the loop checks the condition i < 5
. If the condition is true, the loop will continue executing and repeat the code block. The loop will stop only when the condition becomes false.
Let's have another example:
1
2
3
4
let num = 100;
do {
num += 5;
In this example, we initialise the variable num
and set it to 100. The loop will increment num
by 5 in each iteration until the condition num <= 100
becomes false. The loop will stop when num
is greater than 100.
The do...while
loop is handy when you want to ensure that a code block runs at least once, regardless of the condition. It becomes useful in scenarios when the loop's condition depends on the initial state of variables.