Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 22, 2021 09:59 pm GMT

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);
console.log(myArray); will display [ 10 ]console.log(i); will display 11
  • 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 ourArray is [10]. Essentially, a do...while loop ensures that the code inside the loop will run at least once.

Original Link: https://dev.to/rthefounding/iterate-with-javascript-do-while-loops-1aci

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To