2.2 - Do While

Similar to the While loop, but it always runs at least once


  • The While loop might never run, depending on the condition:

let raining = false;

while (raining) {

console.log("It's raining, I need an umbrella.");


// The loop above will not run. Not even once.

Notice that the while loop has the condition at the beginning.

Do While

  • The do-while loop is similar, but it places the condition at the end of the loop.

let raining = false;

do {

console.log("It's raining! I need an umbrella.");

} while (raining);

In the above example, even though raining is false, we will still see the printout on the console. The check is at the end of the loop.

You might want to run the loop at least once. For example, getting user input.

let input;

do {

input = prompt("Please enter a number from 1 to 5");

input = Number(input);

} while ((isNaN(input)) || (input < 1) || (input > 5));

Notice that the variables raining and input were declared before the loops, not inside. This is crucial.

Repeating Code with Do-While Loops

What if you need a block of code to happen repeatedly? In programming, this is called a loop. There are three basic loops and today we will discuss two of them: While and Do While.

Scrimba demo on While Loops (recorded live in class last year)

OLD Scrimba demo on While Loops

w3schools page on While Loops

Today's Task(s) / Homework

We will practice the Do...While in Replit.