Do While Loop
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 43 of 77.
The do...while loop is similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop will always run the code once, and then it will check if it should continue.
Here's the syntax of a do...while loop:
do {
code;
} while (condition);The code inside the do block is executed first.
Then, the condition inside the while is evaluated. If the condition is true, the loop continues to the next iteration. If the condition is false, the loop stops.
Let's look at an example:
let count = 0;
do {
console.log(count);
count++;
} while (count < 5);This code will output:
0
1
2
3
4Even if the initial value of count is greater than or equal to 5, the code inside the do block will still be executed once.
For example:
let count = 6;
do {
console.log(count);
count++;
} while (count < 5);This code will output:
6Use cases for do...while loops are less common than for or while loops, but they can be useful in situations where you need to ensure that a block of code is executed at least once, regardless of the condition.
Challenge
BeginnerWrite a do...while loop that starts with a variable count set to 5. The loop should:
- Print the current value of
count. - Decrease
countby 1 after each iteration. - As long as
countis bigger than 0
Cheat sheet
The do...while loop executes code at least once before checking the condition:
do {
code;
} while (condition);The code inside the do block runs first, then the condition is evaluated. If true, the loop continues; if false, it stops.
let count = 0;
do {
console.log(count);
count++;
} while (count < 5);Even if the condition is initially false, the code executes once:
let count = 6;
do {
console.log(count);
count++;
} while (count < 5);
// Output: 6Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False