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 …


This content originally appeared on DEV Community and was authored by Randy Rivera

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.


This content originally appeared on DEV Community and was authored by Randy Rivera


Print Share Comment Cite Upload Translate Updates
APA

Randy Rivera | Sciencx (2021-04-22T21:59:45+00:00) Iterate with JavaScript Do…While Loops. Retrieved from https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/

MLA
" » Iterate with JavaScript Do…While Loops." Randy Rivera | Sciencx - Thursday April 22, 2021, https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/
HARVARD
Randy Rivera | Sciencx Thursday April 22, 2021 » Iterate with JavaScript Do…While Loops., viewed ,<https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/>
VANCOUVER
Randy Rivera | Sciencx - » Iterate with JavaScript Do…While Loops. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/
CHICAGO
" » Iterate with JavaScript Do…While Loops." Randy Rivera | Sciencx - Accessed . https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/
IEEE
" » Iterate with JavaScript Do…While Loops." Randy Rivera | Sciencx [Online]. Available: https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/. [Accessed: ]
rf:citation
» Iterate with JavaScript Do…While Loops | Randy Rivera | Sciencx | https://www.scien.cx/2021/04/22/iterate-with-javascript-do-while-loops/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.