Example

for Loops

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
    <title>for Loops</title></head>
<body>
<!--
    Loops are all about doing the same thing over and over again i.e for rapidly completing repetitive tasks.
    Types of loops in JavaScript:
        for loop
        for ... of loop
        for ... in loop
        while loop
-->  

    <h1>Demo: JavaScript for Loops </h1>

    <div>
        <h2>Adding all single digit numbers in an array, using for loop</h2>
        <p id="para1"></p>
    </div>

    <div>
        <h2>Find sum of all the number in an array, using "for loop"</h2>
        <p id="para2"></p>
    </div>

    <div>
        <h2>Nested "for" loop example</h2>
        <p>NOTE: Check the output on console log.</p>
    </div>
    
    <div>
        <h2>Iterate multi-dimension array using "for" loop </h2>
        <p>NOTE: Check the output on console log.</p>
    </div>

    <div>
        <h2>Iterating arrays using "for .. of" loop </h2>
        <p id="para3"></p>
    </div>

    <div>
        <h2>Iterating string using "for .. of" loop</h2>
        <p id="para4"></p>
    </div>


    <div>
        <h2>Use "for .. in" loop to iterate Object literals</h2>
        <p>NOTE: Check the output on console log.</p>
    </div>

    <div>
        <h2>Iterate values in Object methods - turn data into an array</h2>        
        <p id="para5"></p>
        <p id="para6"></p>
    </div>

    <script>


        /************************************************/
        // "for" loop     
        // Example : Adding all single digit numbers in an array, using for loop
        //
        let singleDigit;
        const numArray = [];
        let index = 0;
        for (singleDigit = 0; singleDigit <= 9; singleDigit += 1) {
            numArray[index] = singleDigit;
            index++;
            document.getElementById('para1').innerHTML = 
            `The "numArray" contains = [${numArray}]`;
        }
        /************************************************/
        // Tracing for loop
        //
        // 1st: singleDigit=0; true; o/p: 0 added to the array
        // 2nd: singleDigit=1; true; o/p: 1 added to the array
        // 3rd: singleDigit=2; true; o/p: 2 added to the array
        // ....
        // .... continue adding to the array
        // ....
        // 9th: singleDigit=8; true; o/p: 8 added to the array
        // 10th:singleDigit=9; true: o/p: 9 added to the array
        // 11th:singleDigit=10; false; exit the for loop
        /************************************************/


        /************************************************/
        // "for" loop 
        // Example : Find sum of all the number in an array, using "for loop"
        //
        let evenNum = [22, 44, 66];    // array length = 3
        let sumNum = 0;
        for (let x = 0; x < evenNum.length; x++) {
            sumNum = sumNum + evenNum[x];
        }
        document.getElementById('para2').innerHTML = 
        `Sum of all the number in an array = ${sumNum}`;
        /************************************************/
        // Tracing for loop
        //
        // 1st: x = 0; true; sumNum = 0 + 22 = 22
        // 2nd: x = 1; true; sumNum = 22 + 44 = 66
        // 3rd: x = 2; true; sumNum = 66 + 66 = 132
        // 4th: x = 3; false; Exit the for loop
        // Sum of all the number in an array =   132 
        /************************************************/


        /************************************************/
        // Nested "for" loop example
        //
        for (let p = 1; p <= 2; p++) {  //p:  1,2 
            console.log(`p is: ${p}`)  
            for (let q = 1; q < 4; q++) {   //q: 1,2,3
                console.log(`    q is: ${q}`)
            }
        }
        /************************************************/
        // Output on console.log() looks like this :
        //
        // p is: 1
        //     q is: 1
        //     q is: 2
        //     q is: 3
        // p is: 2
        //     q is: 1
        //     q is: 2
        //     q is: 3
        //
        /************************************************/ 
        // Tracing for loop
        //
        // Outer for loop - 1st of p: p = 1; true; o/p: p is:1
        // 1st of q: q = 1; true; o/p: q is:1
        // 2nd of q: q = 2; true; o/p: q is:2
        // 3rd of q: q = 3; true; o/p: q is:3
        // 4th of q: q = 4; false; Exit the inner q loop
        // Outer for loop - 2nd of p: p = 2; true; o/p: p is:2
        // 1st of q: q = 1; true; o/p: q is:1
        // 2nd of q: q = 2; true; o/p: q is:2
        // 3rd of q: q = 3; true; o/p: q is:3
        // 4th of q: q = 4; false; Exit the inner q loop
        // Outer for loop - 3rd of p: p = 3; false; Exit the outer p loop
        /************************************************/


        /************************************************/
        // Iterate multi-dimension array using "for" loop 
        // Example : Print the country name and Flag colors
        //
        const arrFlags = [  
            ["INDIA","Orange","White","Green"],  
            ["GERMANY","Black","Red","Yellow"],  
            ["RUSSIA","White","Red","Blue"],
            ["COLOMBIA","Yellow","Blue","Red"],
            ["EGYPT","Red","White","Black"]  
        ]

        for (let a = 0; a < arrFlags.length; a++) {   // arrFlags.length = 5
            let flagRow = arrFlags[a];  
            console.log(flagRow[0] + " Flag Colors");  
            for (let b = 1; b < flagRow.length ; b++) {   // flagRow.length = 4
                console.log(flagRow[b]);
            }
        }
        /************************************************/
        // Output on console.log() looks like this :
        //
        // INDIA Flag Colors
        // Orange
        // White
        // Green
        // GERMANY Flag Colors
        // Black
        // Red
        // Yellow
        // RUSSIA Flag Colors
        // White
        // Red
        // Blue
        // COLOMBIA Flag Colors
        // Yellow
        // Blue
        // Red
        // EGYPT Flag Colors
        // Red
        // White
        // Black
        //
        /************************************************/
        // Tracing for loop
        //
        // Outer for loop - 1st of a: a = 0; true; flagRow = ["INDIA","Orange","White","Green"] ; O/P: INDIA Flag Colors
        // 1st of b: b = 1; true : O/P: Orange
        // 2nd of b: b = 2; true : O/P: White
        // 3rd of b: b = 3; true : O/P: Green
        // 4th of b: b = 4; false  Exit the inner b loop
        // Outer for loop - 2nd of a: a = 1; true; flagRow = ["GERMANY","Black","Red","Yellow"] ; O/P: GERMANY Flag Colors
        // 1st of b: b = 1; true : O/P: Black
        // 2nd of b: b = 2; true : O/P: Red
        // 3rd of b: b = 3; true : O/P: Yellow
        // 4th of b: b = 4; false  Exit the inner b loop
        // ... continue 
        /************************************************/


        /************************************************/
        // Iterating arrays using "for .. of" loop 
        // Example : Sum of all the number in an array
        //
        let total = 0;
        let arrayNum = [10, 20, 30, 40];  
        for (let n of arrayNum) {  
            total = total + n;  
        }
        document.getElementById('para3').innerHTML = 
        `Sum of all the number in an array = ${total}`; 
        /************************************************/
        // Tracing for loop
        //
        // 1st : n = 10; total = 0 + 10 = 10
        // 2nd : n = 20; total = 10 + 20 = 30
        // 3rd : n = 30; total = 30 + 30 = 60
        // 4th : n = 40; total = 60 + 40 = 100
        // No more values in the array, hence exit the for loop
        // Sum of all the number in an array = 100
        /************************************************/


        /************************************************/
        // Iterating string using "for .. of" loop 
        // Example : convert string into an array of characters
        //
        const charArray = [];
        let charIndex = 0;
        for (let singleChar of "SKILLZAM") {
            charArray[charIndex] = singleChar;
            charIndex++;
        }
        document.getElementById('para4').innerHTML = 
        `The "charArray" contains = [${charArray}]`;
        /************************************************/
        // Tracing for loop
        //
        // 1st: singleChar = S; o/p: S is added to the array
        // 2nd: singleChar = K; o/p: K is added to the array
        // 3rd: singleChar = I; o/p: I is added to the array
        // 4th: singleChar = L; o/p: L is added to the array
        // 5th: singleChar = L; o/p: L is added to the array
        // 6th: singleChar = Z; o/p: Z is added to the array
        // 7th: singleChar = A; o/p: A is added to the array
        // 8th: singleChar = M; o/p: M is added to the array
        // No more charaters in the string "SKILLZAM", hence exit the for loop
        // The "charArray" contains =  [S,K,I,L,L,Z,A,M]
        /************************************************/


        /************************************************/
        // "for .. in" loop 
        // Example : Use "for .. in" loop to iterate Object literals
        //
        const bioMessi = {
            name: "Leo Messi",
            team: "PSG",
            position: "Forward",
            height: 170,
            weight: 159,
            birthdate: "24/6/1987",
            age: 35,
            country: "Argentina",
            careerHist: ["PSG","Barcelona","Argentina"], 
            isRetired: false
        }
        for (let bio in bioMessi) {
            console.log(`${bio.toUpperCase()} is ${bioMessi[bio]}`);
        }
        /************************************************/
        // Output on console.log() looks like this :
        //
        // NAME is Leo Messi
        // TEAM is PSG
        // POSITION is Forward
        // HEIGHT is 170
        // WEIGHT is 159
        // BIRTHDATE is 24/6/1987
        // AGE is 35
        // COUNTRY is Argentina
        // CAREERHIST is PSG,Barcelona,Argentina
        // ISRETIRED is false
        //
        /************************************************/
        // Tracing for loop
        //
        // 1st: bio = name;        bioMessi[bio] = Leo Messi; o/p: NAME is Leo Messi
        // 2nd: bio = team;        bioMessi[bio] = PSG;       o/p: TEAM is PSG
        // 3rd: bio = position;    bioMessi[bio] = Forward;   o/p: POSITION is Forward
        // 4th: bio = height;      bioMessi[bio] = 170;       o/p: HEIGHT is 170
        // 5th: bio = weight;      bioMessi[bio] = 159;       o/p: WEIGHT is 159
        // 6th: bio = birthdate;   bioMessi[bio] = 24/6/1987; o/p: BIRTHDATE is 24/6/1987
        // 7th: bio = age;         bioMessi[bio] = 35;        o/p: AGE is 35
        // 8th: bio = country;     bioMessi[bio] = Argentina; o/p: COUNTRY is Argentina
        // 9th: bio = careerHist;  bioMessi[bio] = PSG,Barcelona,Argentina; o/p: CAREERHIST is Paris Saint-Germain,Barcelona,Argentina
        // 10th: bio = isRetired;  bioMessi[bio] = false;    o/p: ISRETIRED is false
        // No more name:value pair exists in the object literal, hence exit the for loop
        /************************************************/


        /************************************************/
        // "for .. of" loop on Object
        // Example : Iterate values in Object methods - turn data into an array
        //
        const goalScores = {
            Messi:     44,
            Ronaldo:   43,
            Diogo:     43,
            Robert:    39,
            Turpel:    37,
            Suarez:    36,
            Salah:     35,
            Griezmann: 35,
            Cifuente:  34,
            Kane:      33
        }
        let gTotal = 0;
        // Using Object constructor, create array of 'values'
        let goals = Object.values(goalScores); 
        // goals = [44,43,43,39,37,36,35,35,34,33]
        for (let goal of goals) {
            gTotal += goal;    
        }
        document.getElementById('para5').innerHTML = 
        `The array of object values is = [${goals}]`;
        document.getElementById('para6').innerHTML = 
        `Total goals scored by top 10 players in the year 2018: ${gTotal}`

    </script>
    
</body>
</html>


Output

View original