Do-While Loop
Similar to the while
loop, the do-while
loop is a type of loop in JavaScript that allows you to execute a block of code repeatedly until a certain condition is met.
However, unlike the while
loop, the do-while
loop guarantees that the code block is executed at least once before the condition is checked. This means that even if the condition is false
from the start, the code block will still run once before the loop exits.
The syntax for a do-while
loop is:
while vs do-while
Both loops are used to execute a block of code repeatedly until a certain condition is met. However, they have a few differences in how they work:
- The
while
loop first checks the condition, and then executes the code block only if the condition istrue
. If the condition isfalse
from the start, the code block won't be executed at all. - The
do-while
loop executes the code block first, and then checks the condition. This means that the code block is always executed at least once, even if the condition isfalse
from the start.
Here's an example to illustrate the difference:
In this example, the while
loop won't execute the code block at all, because i
is not greater than 0
from the start. On the other hand, the do-while
loop will execute the code block once, even though i is not greater than 0
from the start.
So, when to use which loop? In general, you can use a while loop
when you want to repeat a block of code only if a condition is true
from the start. Use a do-while
loop when you want to make sure that a block of code is executed at least once, even if the condition is false
from the start.
In the exercise below, drag and drop the correct words to complete the sentences about the loops.