Basic Loops

Do-while Loop

🙋 Need help? Ask an expert now!

The do-while loop is extremely similar to the while loop but with one difference. No matter what the condition evaluates to, it will always run the block of code once. In short, the do-while loop executes the block of statements before checking if the condition is true, and the repeats the block of statements until the condition is false. The do-while loop is used when you want to run a loop at least once no matter what the expression is.

The do-while loop above has the exact same function as the while loop we worked with in the previous card. It prints the numbers 1 through 10 in order. If you change the initial value of counter to 11, the loop will still run once and print 11 even though the condition counter < 11 is false. The do-while is only used in special cases where you know the condition could possibly be false before even running the while loop, thus executing the code block before testing the condition.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let varOne = 20;
            do {
            while (varOne < 20);

What is the last number printed on the console after running the code above?