JavaScript - tutorial - 06 - loops

revision:


Content

Loops allow to run the same code over and over again for loop while loop do while loop break continue Nested loops Loop examples


Loops allow to run the same code over and over again

top

Each time however with a different value.

Examples: loop

code:
                <div class="spec">
                    <a id="loop_1"></a>    
                </div>
                <script>
                    var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
                    var text = "";
                    var i;
                    for (i = 0; i < cars.length; i++) {
                        text += cars[i] + " , ";
                    }
                    document.getElementById("loop_1").innerHTML = "array + loop: " + text;
                </script>
            

JavaScript supports different kinds of loops:

for — the most common way to create a loop in JavaScript.

while — sets up conditions under which a loop executes.

do while — similar to the while loop, however, it executes at least once and performs a check at the end to see if the condition is met to execute again.

break — used to stop and exit the cycle at certain conditions.

continue — skip parts of the cycle if certain conditions are met.


for loop

top

Syntax

            for (before loop; condition for loop; execute after loop) { 
what to do during the loop
}
            for ([initialExpression]; [conditionExpression]; [incrementExpression]) statement
        

Statement 1 : before loop : to initialize the variable used in the loop (i = 0).

However, this is not always the case, as statement 1 is optional. Also, many values can be initiated in statement 1 (separated by comma).

Moreobver, you can omit statement 1 when your values are set before the loop starts.

Examples: statement 1 - before loop

code:
                    <div class="spec">
                        <a id="loop_2"></a>      
                    </div>
                    <script>
                        var cars_A = ["BMW", "Volvo", "Saab", "Ford"];
                        var i, len, text;
                        for (i = 0, len = cars_A.length, text = ""; i < len; i++) {
                            text += cars_A[i] + " , ";
                        }
                        document.getElementById("loop_2").innerHTML = "cars array: " + text;
                    </script>
                

Examples - statement 1 omitted

code:
                    <div class="spec">
                        <a id="loop_3"></a>     
                    </div>
                    <script>
                        var cars_B = ["BMW", "Volvo", "Saab", "Ford"];
                        var i_B = 2;
                        var len_B = cars_B.length;
                        var text_B = "";
                        for (; i_B < len_B; i_B++) {
                            text_B += cars_B[i_B] + " , ";
                        }
                        document.getElementById("loop_3").innerHTML = "cars array - partial: " + text_B;
                    </script>
                

Examples: statement 1




code:
                    <div>
                        <p class="spec" id="loop_4"></p><br>
                        <p class="spec" id="loop_5"></p><br>
                        <p class="spec" id="loop_6"></p><br>
                        <button onclick="reverse()">reverse the order</button>
                        <p class="spec" id="loop_7"></p>
                    </div>
                    <script>
                        const cars_C = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
                        let text_C = "";
                        for (let i_C = 0; i_C < cars_C.length; i_C++) {
                            text_C += cars_C[i_C] + " , ";
                        }
                        document.getElementById("loop_4").innerHTML = "cars: " + " , " + text_C;
        
                        let text_CC = "";
                        for (let i_CC = 0; i_CC < 5; i_CC++) {
                            text_CC += "the number is: " + i_CC + " , ";
                        }
                        document.getElementById("loop_5").innerHTML = text_CC;
                                        
                        function reverse() {
                            var cars_CCC = ["BMW", "Volvo", "Saab", "Ford"];
                            var text_CCC = "";
                            var i_CCC;
                            for (i_CCC = cars_CCC.length - 1; i_CCC >= 0; i_CCC--) {
                                text_CCC += cars_CCC[i_CCC] + " , ";
                            }
                            document.getElementById("loop_6").innerHTML = "cars: " + " ," + text_CCC;
                        }
                    </script>
                



code:
                    <div>
                        <p class="spec" id="loop_8"></p><br>
                        <p class="spec" id="loop_9"></p><br>
                     </div>
                     <script>
                         const cars_D = ["BMW", "Volvo", "Saab", "Ford"];
                         let a_D, len_D, text_D;
                         for (a_D = 0, len_D = cars_D.length, text_D = ""; a_D < len_D; a_D++) {
                              text_D += cars_D[a_D] + " < , ";
                         }
                         document.getElementById("loop_8").innerHTML = "cars: " + "< , " + text_D;
         
                         const cars_DD = ["BMW", "Volvo", "Saab", "Ford"];
                         let i_DD = 2;
                         let len_DD = cars_DD.length;
                         let text_DD = "";
         
                         for (; i_DD < len_DD; i_DD++) {
                             text_DD += cars_DD[i_DD] + "< , ";
                         }
                         document.getElementById("loop_9").innerHTML = "cars: " + "< , " + text_DD;
                     </script>
                

Statement 2 : condition for loop : to evaluate the condition of the initial variable.

Howver, this is not always the case, as statement 2 is also optional. If statement 2 returns true, the loop will start over again; if it returns false, the loop will end.

If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser.

Often statement 2 is used to evaluate the condition of the initial variable

Examples - statement 2



code:
                    <div class="spec">
                        <p id="loop_10"></p><br>
                        <button onclick="loopThrough()">try it</button>
                        <p id="loop_11"></p><br>
                    </div>
                    <script>
                        let num = " ";
                        for (let jj = 1;; jj += 2) {
                            num += jj + " , ";
                            if (jj > 10) {
                                break;
                            }
                        }
                        document.getElementById("loop_10").innerHTML = num;
        
                        function loopThrough() {
                            var cars_Y = ["BMW", "Volvo", "Saab", "Ford"];
                            var text_Y = "";
                            var i_Y;
                            for (i_Y = 0;; i_Y++) {
                                if (i_Y == 3) {
                                break;
                                }
                                text_Y += cars_Y[i_Y] + " , ";
                            }
                            document.getElementById("loop_11").innerHTML = "cars: " + " , " + text_Y;
                        }
                    </script>
                

Statement 3 : execute after loop : increment the value of the initial variable.

However, statement 3 is optional. Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. Statement 3 can also be omitted, when you increment your values inside the loop.

Examples - statement 3

code:
                    <div class="spec">
                        <a id="loop_12"></a>    
                    </div>
                    <script>
                        var cars_E = ["BMW", "Saab", "Volvo", "Ford"];
                        var i_E = 0;
                        var len_E = cars_E.length;
                        var text_E = "";
                        for (; i_E < len_E; ) {
                            text_E += cars[i_E] + " , ";
                            i_E++;
                        }
                        document.getElementById("loop_12").innerHTML = "cars array: " + text_E;
                    </script>
                

"for ... in" loop : loops through the properties of an object.

Syntax: for (key in object) { // code block to be executed}

Examples: for..in loop

code:
                    <div class="spec">
                        <a id="loop_13"></a>      
                    </div>
                    <script>
                        var txt = "";
                        var person = {fname:"John", lname:"Doe", age:25}; 
                        var x;
                        for (x in person) {
                            txt += person[x] + " , ";
                        }
                        document.getElementById("loop_13").innerHTML = "properties of person: " + txt;
                    </script>
                

code:
                    <div>
                        <p class="spec" id="loop_14"></p>
                        <p class="spec" id="loop_15"></p>
                        <p class="spec" id="loop_16"></p>
                    </div>
                    <script>
                        const person_F = {fname:"Olivier", lname:"Sneyders", age:25}; 
                        let txt_F = "";
                        for (let x_F in person) {
                            txt_F += person_F[x_F] + " ";
                        }
                        document.getElementById("loop_14").innerHTML = "person's details: " + txt_F;
        
                        const object_FF = { a: 1, b: 2, c: 3 };
                        let txt_FF = " ";
                        for (const property in object_FF){
                            txt_FF += `${property}: ${object_FF[property]}` + " , ";
                        }
                        document.getElementById("loop_15").innerHTML = txt_FF;
        
                        const shark = { species: "great white", color: "white", numberOfTeeth: Infinity}
                        let txt_FFF = " ";
                        for (attribute in shark) {
                            txt_FFF += `${attribute}: ${shark[attribute]}` + " , ";
                            document.getElementById("loop_16").innerHTML = txt_FFF;
                        }
                    </script>
                

"for-in" loops - longhand and shorthand

longhand

                const obj = {
                    a: 1,
                    b: 2,
                    c: 3,
                };
                const keys = Object.keys(obj);
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];
                    const value = obj[key];
                    // ...
                }
            

shorthand

                const obj = {
                    a: 1,
                    b: 2,
                    c: 3,
                };
                for (const key in obj) {
                    const value = obj[key];
                    // ...
                }
            

"for ... of" loop : loops through the values of an iterable object.

An iterable object is an object that has iterable properties.

Syntax: for (variable of iterable) { // code block to be executed }

The "for...of" statement loops over data structures that are iterable such as arrays, strings, maps, nodelists, and more.

With respect to the variable, for every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.

Examples: for...of loop

code:
                    <div class="spec">
                        <a id="for_G01"></a>    
                    </div>
                    <script>
                        var cars_G = ["BMW", "Volvo", "Mini"];
                        var x_G;
                        for (x_G of cars_G) {
                            document.getElementById("loop_17").innerHTML += "car: " + x_G +", ";  
                        }
                        
                    </script>
                

code:
                    <div>
                        <p class="spec" id="loop_18"></p>
                        <p class="spec" id="loop_19"></p>
                    </div>
                    <script>
                        let language = "JavaScript";
                        let txt_H = "";
                        for (let x_H of language) {
                            txt_H += x_H + " , ";
                        }
                        document.getElementById("loop_18").innerHTML = txt_H;
        
                        let sharks_H = [ "great white", "tiger", "hammerhead" ];
                        let txt_HH = " "
                        for (let shark_H of sharks_H) {
                            txt_HH += shark_H + " , ";
                        }
                        document.getElementById("loop_19").innerHTML = txt_HH;
                    </script>
                

"for-of" loops - longhand and shorthand

longhand

                const arr = [1, 2, 3, 4, 5];
                for (let i = 0; i < arr.length; i++) {
                    const element = arr[i];
                // ...
                }
            

shorthand

                const arr = [1, 2, 3, 4, 5];
                for (const element of arr) {
                    // ...
                  }
            

the for loop without the loop body

The for statement can have an empty statement. In this case, a semicolon ( ;) is placed immediately after the for statement.

Examples: without loop body

code:
                        <div>
                            <p id="loop_20"></p>
                        </div>
                        <script>
                            let sum = 0;
                            for (let m = 0; m <= 9; m++, sum += m);
                            document.getElementById("loop_20").innerHTML = "sum: " + sum;
                            console.log(sum);
                        </script>
                    

nested loops

The first loop is often called an "outer loop", and the second is often called the "inner loop" because it is inside the first, outer loop.

The outer loop executes first, and for each time the outer loop is executed, the inner loop will also execute.

Examples: outer and inner loops


code:
                        <div>
                            <button onclick="nest()">try it</button>
                            <p class="spec" id="loop_21"></p><br>
                        </div>
                        <script>
                            function nest() {
                                var text_A = "";
                                var o, p;
        
                                for (o = 0; o < 3; o++) {
                                    text_A += " ," + "o = " + o + ", p = ";   
                                    for (p = 10; p < 15; p++) {
                                        document.getElementById("loop_21").innerHTML = text_A += o + " ";
                                    }
                                }
                            }
                        </script>
                    

JavaScript "for" loop

This shorthand/trick is really useful if you want plain JavaScript and don't want to rely on external libraries, such as jQuery or lodash.

longhand

                        const fruits = ['mango', 'peach', 'banana'];
                        for (let i = 0; i < fruits.length; i++)
    
                        for (let i = 0; i < myArr.length; i++) { 
                            console.log(myArr[i]); 
                          } 
                    

shorthand

                        for (let fruit of fruits)
                        for (let index in fruits) //If you just want to access the index.
    
                        for (const val of myArr) { 
                            console.log(val); 
                          } 
    
                        for (const index in myArr) { 
                            console.log(`index: ${index} and value: ${myArr[index]}`); 
                          }
                    
                        const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
                        for (let key in obj)
                        console.log(key) // output: continent, country, city
                    

some more examples

database: Chris, Sarah, Bill, Mary, Dianne

code:
                    <div class="spec">
                        <p>database: Chris, Sarah, Bill, Mary, Dianne</p>
                        <label for="search">Search by contact name: </label>
                        <input id="search" type="text">
                        <button id="button">Search</button>
                        <a id="result"></a>         
                    </div>
                    <script>
                        const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 
                        'Dianne:9384975'];
                        const para = document.querySelector('#result');
                        const input = document.querySelector('input');
                        const btn = document.querySelector('#button');
            
                        btn.addEventListener('click', function() {
                            const searchName = input.value.toLowerCase();
                            input.value = '';
                            input.focus();
                            for(let i = 0; i < contacts.length; i++) {
                                let splitContact = contacts[i].split(':');
                                if(splitContact[0].toLowerCase() === searchName) {
                                    para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
                                    break;
                                } else {
                                    para.textContent = 'Contact not found.';
                                }
                            }
                        });

                    </script>  
                

while loop

top

The while loop loops through a block of code as long as a specified condition is true.

Syntax

        while (condition){ 
code/ loop body
}

Examples: loop through the numbers

code:
                    <div class="spec">
                        <a id="loop_22"></a>      
                    </div>
                    <script>
                        var text_J = "";
                        var i_J = 0;
                        while (i_J < 10) {
                            text_J += "the number is: " + i_J + " ,<br>";
                            i_J++;
                        }
                        document.getElementById("loop_22").innerHTML = text_J;
                    </script>
                

P.S. the code in the loop will run, over and over again, as long as a variable (i_J) is less than 10.

Examples: my cats

code:
                    <div class="spec">
                        <a id="loop_23"></a>      
                    </div>
                    <script>
                        const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
                        let info = 'My cats are called:';
                        let param = document.querySelector('#loop_23');
                        let e = 0;
                        while(e < cats.length) {
                        if(e === cats.length - 1) {
                            info += 'and ' + cats[e] + '.';
                        } else {
                            info += cats[e] + ', ';
                        }
                        e++;
                        }
                        param.textContent = info;
                    </script>
                

some more examples

code:
                    <div>
                        <p class="spec" style="margin-left:5vw;" id="loop_24"></p>
                        <p class="spec" style="margin-left:5vw;" id="loop_25"></p>
                        <p class="spec" style="margin-left:5vw;" id="loop_26"></p>
                    </div>
                    <script>
                        let tekst = "";
                        let ii = 0;
                        while (ii < 10) {
                            tekst += "<br> - The number is " + ii;
                            ii++;
                        }
                        document.getElementById("loop_24").innerHTML = tekst;
            
                        const cars_ab = ["BMW", "Volvo", "Saab", "Ford"];
                        let kk = 0;
                        let text_a = "";
                        while (cars_ab[kk]) {
                            text_a += cars_ab[kk] + " , ";
                            kk++;
                        }
                        document.getElementById("loop_25").innerHTML = "cars:" + text_a;
            
                        let rands = [];
                        let count = 0;
                        const size = 5;
                        let sentence = ""
                        while(count < size) {
                            rands.push(Math.round(Math.random() * 10));
                            count++;
                            sentence += "the current size of the arrary is " + count + "<br>" ;
                            document.getElementById("loop_26").innerHTML = sentence;
                        }
                    </script>
                

do while loop

top

A variant of the while loop, which will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {loop body} 
while (condition)

The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.

Examples: do..while loop

code:
                    <div class="spec">
                        <a id="loop_27"></a>
                    </div>        
                    <script>
                        var text_K = ""
                        var i_K = 0;
                        
                        do {
                            text_K += "The number is: " + i_K + " ,<br>";
                            i_K++;
                        }
                        while (i_K < 10);  
                        document.getElementById("loop_27").innerHTML = text_K;
                    </script>
                

code:
                    <div class="spec">
                        <a id="loop_28"></a>       
                    </div>
                    <script>
                        const cats1 = ['Bill', 'Jeff', 'Jasmin', 'Pete', 'Biggles'];
                        let info1 = 'My cats are called:';
                        const parag = document.querySelector("#loop_28");
                        let h = 0;
                        do {
                            if(h === cats1.length - 1) {
                                    info1 += 'and ' + cats1[h] + '.';
                            } else {
                                info1 += cats1[h] + ', ';
                            }
                            h++;
                        } while(h < cats1.length);
                        parag.textContent = info1;
                    </script>
                

break

top

The break statement can be used to jump out of a loop. It breaks the loop and continues executing the code after the loop (if any).

A loop exits when its condition becomes falsy, but it can be forced to exit at any time using the "break" directive.

Examples: break

code:
                    <div class="spec">
                        <a id="loop_29"></a>     
                    </div> 
                    <script>
                        var text_L = "";
                        var i_L;
                        for (i_L = 0; i_L < 10; i_L++) {
                            if (i_L === 3) { break; }
                            text_L += "the number is " + i_L + " ,<br>";
                        }
                        document.getElementById("loop_29").innerHTML = text_L;
                    </script>
                

Click the button to do a loop with a break.

code:
                    <div>
                        <p>Click the button to do a loop with a break. </p>
                        <button onclick="stopLoop()">try it</button>
                        <p id="loop_30"></p>
                    </div>
                    <script>
                    function stopLoop() {
                            var text_M = "";
                            var l = 0;
                            while (l < 5) {
                                text_M += "<br>The number is " + l;
                                l++;
                                if (l === 3) {
                                    break;
                                }
                            }
                            document.getElementById("loop_30").innerHTML = text_M;
                        }
                    </script>
                

continue

top

The "continue" statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

the "continue" directive doesn't stop the whole loop, but stops the current iteration and forces the loop to start a new one (if the condition allows).

Examples: continue


code:
                    <div class="spec">
                        <a id="loop_31"></a><br>     
                    </div>
                    <script>
                        var text_N = "";
                        var i_N;
                        for (i_N = 0; i_N < 10; i_N++) {
                            if (i_N === 3) { continue; }
                            text_N += "the number is: " + i_N + ", " +"<br>" ;
                        }
                        document.getElementById("loop_31").innerHTML = text_N;
                    </script>
                

Click the button to do a loop which will skip a step.

code:
                    <div>
                        <p> Click the button to do a loop which will skip a step.</p>
                        <button onclick="skipStep()">try it</button>
                        <p id="loop_32"></p>
                    </div>
                    <script>
                    function skipStep() {
                            var text_O = "";
                            var m_O = 0;
                            while (m_O < 5) {
                                m_O++;
                                if (m_O === 3) {
                                continue;
                                }
                            text_O += "<br>The number is " + m_O;
                            }
                            document.getElementById("loop_32").innerHTML = text_O;
                    }
                    </script>
                

Nested loops

top

Nested loops is a coding pattern that enables you to perform a looping code inside the first loop.

Examples: nested loops

code:
                <div>
                    <p class="spec" id="loop_33"></p>
                    <p class="spec" id="loop_34"></p>
                    <p class="spec" id="loop_35"></p>
                    <p class="spec" id="loop_36"></p>
                    <p class="spec" id="loop_37"></p>
                    <p class="spec" id="loop_38"></p>
                    <p class="spec" id="loop_39"></p>
                  
                </div>
                <script>
                    let n = 1;
                    let text_d = " ";
                    while(n <= 10) {
                        if( n%2 == 0){
                            text_d += "<br> even number: " + n + ";";
                        }
                        n++;
                        document.getElementById("loop_33").innerHTML = text_d;
                    }
        
                    for (let i = 0; i <= 2; i++) {
                        document.getElementById("loop_34").innerHTML = "- First level loop";
                        document.getElementById("loop_35").innerHTML = "- First level loop";
                        document.getElementById("loop_36").innerHTML = "- First level loop";
                        for (let j = 0; j <= 3; j++) {
                            document.getElementById("loop_37").innerHTML = "-- Second level loop";
                            document.getElementById("loop_38").innerHTML = "-- Second level loop";
                            document.getElementById("loop_39").innerHTML = "-- Second level loop";
                        }
                    }
                </script>
            

Loop examples

top
JavaScript.info - examples
the 'while' loop:
                let i = 0;
                while (i < 3) { // shows 0, then 1, then 2
                alert( i );
                i++;
                }
                
                let i = 3;
                while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
                    alert( i );
                    i--;
                }

                let i = 3;
                while (i) alert(i--);
            
the "do ... while" loop:
                let i = 0;
                do {
                alert( i );
                i++;
                } while (i < 3);
            
the 'for' loop:
                for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
                    alert(i);
                }

                for (let i = 0; i < 3; i++) {
                    alert(i); // 0, 1, 2
                }
                alert(i); // error, no such variable

                let i = 0;
                for (i = 0; i < 3; i++) { // use an existing variable
                    alert(i); // 0, 1, 2
                }
                alert(i); // 3, visible, because declared outside of the loop

                let i = 0; // we have i already declared and assigned
                for (; i < 3; i++) { // no need for "begin"
                    alert( i ); // 0, 1, 2
                }

                let i = 0;
                for (; i < 3;) {
                    alert( i++ );
                }
            
breaking the loop:
                let sum = 0;
                while (true) {
                    let value = +prompt("Enter a number", '');
                    if (!value) break; // (*)
                    sum += value;
                }
                alert( 'Sum: ' + sum )
            
continue to the next iteration:
                for (let i = 0; i < 10; i++) {
                    // if true, skip the remaining part of the body
                    if (i % 2 == 0) continue;
                    alert(i); // 1, then 3, 5, 7, 9
                }
            
            
labels for break/continue:
                for (let i = 0; i < 3; i++) {
                    for (let j = 0; j < 3; j++) {
                        let input = prompt(`Value at coords (${i},${j})`, '');
                        // what if we want to exit from here to Done (below)?
                    }
                }
                alert('Done!');

                outer: for (let i = 0; i < 3; i++) {
                    for (let j = 0; j < 3; j++) {
                    let input = prompt(`Value at coords (${i},${j})`, '');   // if an empty 
                    string or canceled, then break out of both loops
                    if (!input) break outer; // (*)
                    // do something with the value...
                    }
                }
                alert('Done!');
        
"switch" statement:
                let a = 2 + 2;
                switch (a) {
                    case 3:
                        alert( 'Too small' );
                        break;
                    case 4:
                        alert( 'Exactly!' );
                        break;
                    case 5:
                        alert( 'Too big' );
                        break;
                    default:
                        alert( "I don't know such values" );
                }

                let a = 2 + 2;
                switch (a) {
                    case 3:
                        alert( 'Too small' );
                    case 4:
                        alert( 'Exactly!' );
                    case 5:
                        alert( 'Too big' );
                    default:
                        alert( "I don't know such values" );
                }

                let a = 3;
                switch (a) {
                    case 4:
                        alert('Right!');
                        break;
                    case 3: // (*) grouped two cases
                    case 5:
                        alert('Wrong!');
                        alert("Why don't you take a math class?");
                        break;
                    default:
                        alert('The result is strange. Really.');
                }