Intro to Programming Nanodegree program - javascript - javascript while loop

Performing Actions Until a Condition is no Longer True Using Javascript While Loops

The Javascript while loop is a programming construct that executes a set of statements as long as a certain condition is true. While loops are part of a programming statement class called “control statements,” since they influence the logical flow of a program.

The Javascript standard specifies two different types of while loops: the simple while loop and the do-while loop. Although they have similar functions, important differences between them make them useful in slightly different circumstances.

In this article, we define what a Javascript while loop is and how it differs from the do-while loop. This article also covers some caveats when using either of those loops.

Javascript While Loops

A Javascript while loop always starts with the keyword while followed by an expression in parentheses. This expression, called the end condition, determines when the while loop should stop executing the instructions in its code block.

A while loop looks like this:

while (condition) {
    ... instructions ...
}

Javascript while loops only execute the instructions they contain if the end condition has not yet been met. Before each iteration of a while loop, the loop evaluates its end condition clause, and if the condition clause has been met, it doesn’t execute the instructions within.

Therefore, depending on the program statements before the while loop, it may never be executed. For example, in the following examples, the first while loop would execute its instructions, and the second while loop never would.

let x = 10;
while (x > 1) {
    x = x - 1;
}

// at this point x equals 1
while (x > 2) {
    x = x + 1; // this statement is never executed
}

To stop a while loop from within, use the reserved keyword break to jump out of the loop, terminating further execution of the instructions inside the loop.

This while loop, for example, terminates when one of its variables reaches a certain value independently of the end condition.

let x = 5;
let y = someFunction();

while (x > 0) {
    if (y == 100) { break; }
    ... instructions ...
}

// the break causes execution to continue here

Nesting Javascript while loops is also possible. Like other types of loops and nested statements, however, it can be difficult to trace the contents of deeply-nested loops during code maintenance.

while (end condition 1) {
    ... instructions ...
    while (end condition 2) {
        ... instructions ...
    }
}

Javascript Do-While Loops

A Javascript do-while loop always starts with the keyword do followed by a code block. The keyword while, and an end condition in parentheses, appear after the code block.

The do-while loop looks like an inverted version of the while loop, like this:

do {
    ... instructions ...
} while (end condition);

Since a do-while loop does not evaluate its end condition until after it executes its code block, the instructions inside a do-while loop always execute at least once. This is in contrast to a simple while loop, which skips its code block immediately if its end condition is met.

Like a while loop, you can end execution of a do-while loop’s code block early with the keyword break. Nesting of do-while loops is also possible.

do {
    ... instructions ...
    do {
        ... instructions ...
        if (y == 100) { break; }
    } while (end condition 2);
    // the break causes execution to continue here
} while (end condition 1);

Caveats of Javascript While Loop Variants

Mismanagement of Javascript while and do-while loops causes a number of problems. They all come from different mistakes in identifying when a loop should stop executing its instructions.

Infinite Loops

Although there are two different ways to end these loops, it is surprisingly easy to create a loop that never meets its end condition. When this happens, Javascript will get “stuck” executing the same code over and over with nothing to stop it, and a programmer has no choice but to end the program manually.

The following loop executes forever because the value of the variable x never reaches zero. A simple programmer mistake, incrementing rather than decrementing the variable, during each iteration ensures that this loop will go on forever.

let x = 2;
while (x != 0) {
    x = x + 1;  // Should be x - 1 here.
}

Unreachable Code

When terminating a while or do-while loop early with the keyword break, it’s important to make sure that a loop has the potential to execute all possible break cases. Putting them in the wrong order can create code that it is impossible for a program to reach.

Unreachable code errors won’t stop your Javascript program from running, but most browsers will print a warning to the console, and the warning might also show up on the page itself.

let x = 4;
while (x > 0) {
    x = x - 1;
    if (x != 0) { break; }
    if (x == 1) { ... instructions ... }  // unreachable!
}

In the above example, the (x == 1) code is unreachable because the previous test will be true for the value 1, and so a break will happen before the unreachable line of code.

Breaking Nested Loops

By default, Javascript terminates only the loop in which it finds the keyword break, so if that keyword occurs inside a nested loop, it will not prevent the outer loops from continuing.

while (end condition 1) {
    ... instructions ...
    while (end condition 2) {
        if (break condition) { break; }
        ... instructions ...
    }
    // the break causes execution to continue here
}

To gain more control over which loop code can break out of, label each loop with a unique name. Then, follow the keyword break with the label of the loop you want to terminate.

outerloop: while (end condition 1) {
    ... instructions ...
    innerloop: while (end condition 2) {
        if (break condition) { break outerloop; }
        ... instructions ...
    }
}

// the break outerloop causes execution to continue here

Conclusion

Javascript while loops and do-while loops are basic Javascript control structures similar to for loops. They each execute instructions repeatedly until a condition is met that prevents further execution, but programmers must make sure the loops’ end conditions are met. Otherwise, the loops will continue running indefinitely.

Enroll in our Intro to Programming Nanodegree Program today to learn more about TOPIC and other programming concepts.

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni