Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

do…while loop – JavaScript

Summary

let i = 0;

do {
  // Insert code here
  i++;
} while (i < 10);

Details

A do…while loop allows you to easily repeat a block of code multiple times.

In a do…while loop, the statement inside the do block will be executed at least once. This is different from a normal while loop. In a normal while loop, it’s possible that the block of code never gets executed at all.

To write a do…while loop, first declare your counter variable. Unlike a for loop, you declare your counter outside of the loop.

let i = 0;

Next, write the skeleton of the do…while loop.

let i = 0;

do {

} while ();

Next, add the test condition inside the parentheses.

let i = 0;

do {

} while (i < 10);

Add an increment or decrement statement to the end of your loop. Without this, you might accidentally create an infinite loop!

let i = 0;

do {

  i++;
} while (i < 10);

Lastly, add the code you want to repeat.

let i = 0;

do {
  console.log("Hello world");
  i++;
} while (i < 10);

Demo

Exercises

Try the following statements in the console:

let i = 0;

do {
  console.log("hello world");
  i++;
} while (i < 5);

You should see ‘hello world’ print out 5 times, or the phrase ‘hello world’ with a number 5 next to it.

References

do...while statement on MDN

Back to: JavaScript Reference > JS Loops