while Loops / while Statements

By: Dusty Arlia
Published on November 1, 2012
Last Updated on Saturday, July 18, 2015 at 7:10 PM
Total Updates: 8

while statements are JavaScript's most basic loop. They will repeat the same piece of code over and over until an expression becomes false. While the expression remains to be true, it will keep on looping (remember this by the saying "true, do"). To prevent an infinite loop, the code inside the while loop body must change the loop condition.

Here is the basic syntax for a while loop.

while (/*loop condition expression*/) {
//This is the loop body.
//Code that gets executed goes here.
//Make sure the loop condition changes.

while loops work great for repetitive tasks. Here is a real example of a while loop:

var count = 1;
while (count < 11){
    document.write(count + ", ");

In this example, the JavaScript interpreter initializes the count variable to the number 1. Next, the JavaScript interpreter has to evaluate the expression count < 11. If it evaluates to true the loop body in between the curly braces ({}) is executed. The expression is evaluated with each loop iteration. As soon as the expression becomes false (in this example: count equals 11) the loop body is skipped over. You will see that the increment operator (++) increments the count variable. This makes the expression change so that there is no infinite loop.