logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

While and Do/While Loops

The While and Do/While Loops are similar to the for loops, but the way we write them is a bit different.

While loop

                   
    var count = 0;

    while (count < 5) {
        console.log(count);
        count++;
    }

    /* The console will show:

    0
    1
    2
    3
    4

    */
                   
               

The logic is the same but just the condition is written inside parenthesis. The startinf variable (var count = 0) needs to be declared before writing the loop and the incremental operator should be written inside the loop.

Do/while loop

The do/while loop works the same way, the only difference is that the condition is written at the end of the loop. This means that this loop always runs at least once, before testing the condition.

                    
        var count = 10;
    
        do {
            console.log(count);
            count++;
        } while (count < 5); // This loop requires the semicolon after the condition.
    
        // The console will show: 10
    
                    
                

Note that the condition never returned true, but since the validation is only done at the end of the first iteration, we were able to run the loop one time before testing the condition.

Contents