Home » Tutorials » JavaScript » While Loop

While Loop

While loops are similar to for loops, but with a different structure. While loops are generally used in places where for loops will not work. For instance, if you want some code to run the entire time the user is on a page, you should use a while loop.

Example var i = 0;
while(i < 5)
{
document.write(i); //write our variable’s value
document.write( “<br/>”); //line break
i++; //increment operator
}
document.write(“End of while loop”);
Result
0
1
2
3
4
End of while loop

After seeing the while loop, you can probably see how it is like the for loop, but just with the first statement being outside of the loop. The conditional remaining in the if like statement. The second statement being embedded in if like statement.

The first statement var i = 0 is simply setting our variable i equal to zero. The conditional statement i < 5 is holding down the fort as the only item in the if like statement. Finally, we get into the function where our increment operator i++; serves to advance if like statement. From the results, we can see that the exact same thing happens here that happened in the previous for loop.

Example var i = 0;
do
{
document.write(i); //write our variable’s value
document.write( “<br/>”); //line break
i++; //increment operator
}
while(i < 5)
document.write( “End of while loop” );
Result
0
1
2
3
4
End of do while loop

Again, pretty similar to the example above, but there is actually one major difference. In the do while loop, the statements in the do while are always run once because the conditional is at the end. The conditional here tells the browser to go back and run through the do part again. We set the variable i equal to 0. Then we run through the do part where we find our increment operator i++;. The results are the same as the previous loops because once the increment operator makes i equal to five, we exit the loop and continue reading onto the next statement, document.write(" End of while loop ");.

References



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "While Loop". After Hours Programming. Accessed on March 19, 2024. https://www.afterhoursprogramming.com/tutorial/javascript/while-loop-js/.

  • Stewart, Suzy. "While Loop". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/javascript/while-loop-js/. Accessed 19 March, 2024.

  • Stewart, Suzy. While Loop. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/javascript/while-loop-js/.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.