The do…while loop in JavaScript does the exact same thing as the while loop with just one actual difference, it runs the piece of code inside the loop at least once at the beginning, before the condition is evaluated.
Syntax
- At first, before the loop even begins, the piece of code inside the loop will run.
- Then, the condition given inside the parenthesis ( ) is checked.
- If the condition is true, the given block of code runs again. If it is false, the given block of code doesn’t run and the loop ends.
Example 1
Output
How do…while loop works in JavaScript? 🤔
Unlike the for loop, the do…while loop doesn’t have sections in it’s syntax where we can initialize a variable and update it. Therefore, we have to declare and update the variable ourselves.
Iteration | Variable | Check Condition (i<3) | Output | Update (i++) |
At the very first time (No iteration has happened yet.) | i=0 | Condition has not been checked yet. | Current value of i is 0. | i=1 |
1st | i=1 | true | Current value of i is 1. | i=2 |
2nd | i=2 | true | Current value of i is 2. | i=3 |
3rd | i=3 | false | No output as the condition is false. | i=4 |
Example 2
Output
Infinite Do…While Loop 😵
The above code blocks will run infinitely, or in some compilers, will return errors.
In this way, a do…while loop runs having a small difference from the while loop.