DEV Community

Randy Rivera
Randy Rivera

Posted on

Iterate with JavaScript Do...While Loops

The next type of loop you will learn is called a do...while loop. It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true.

  • Example:
var myArray = [];
var i = 10;

do {
  myArray.push(i);
  i++;
} while (i < 10);
Enter fullscreen mode Exit fullscreen mode
console.log(myArray); will display [ 10 ]
console.log(i); will display 11
Enter fullscreen mode Exit fullscreen mode
  • In this case, we initialize the value of i to 10. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment i before we get to the while condition. When we finally evaluate the condition i < 10 on the last line, we see that i is now 11, which fails the I < 10 so we exit the loop and are done. At the end of the above example, the value of myArray is [10]. Essentially, a do...while loop ensures that the code inside the loop will run at least once.

Top comments (2)

Collapse
 
dimaldim profile image
Dimitar Dimitrov

I believe you have a typo at "the value of ourArray", it should be myArray instead as you are initializing that

Collapse
 
rthefounding profile image
Randy Rivera

yes it was a typo thank you

Some comments may only be visible to logged-in visitors. Sign in to view all comments.