JavaScript: Loop Exercies

About

Exercises from various learning webpages
This page is housing various loop exercises from various webpages recommended by the Odin project.
Loops covered:
  • for
  • for...of for collection
  • while
  • do...while
Codey Luwak's notes:

Countdown

Task: Launch countdown from 10 to 0 blast off
MDN: Looping code: Active learning: Launch countdown
Using for loop
HTML codes
<button id="forCountdownButton">Start countdown</button>
<div id="forCountdownOutput"></div> 
JS codes (countdown_for.js)
function forCountdown () {
    const output = document.getElementById("forCountdownOutput"); 
    const button = document.getElementById("forCountdownButton");

    if (output.textContent === "") {
        for (let i = 10; i >= 0; i--) {
            const para = document.createElement("p");
            const output = document.getElementById("forCountdownOutput");        
    
            if (i === 10) {
                para.textContent = `Countdown ${i}`;
            } else if (i === 0) {
                para.textContent = "Blast off!";
            } else {
                para.textContent = i;
            }
    
            output.appendChild(para);
        }
        button.textContent = "Close countdown";
    } else {
        output.textContent = "";
        button.textContent = "Start countdown";
    }
}

const forCountdownButton = document.getElementById("forCountdownButton");
forCountdownButton.addEventListener("click", forCountdown);
Using while
HTML codes
<button id="whileCountdownButton">Start countdown</button>
<div id="whileCountdownOutput"></div> 
JS codes (countdown_while.js)
function whileCountdown () {
    const output = document.getElementById("whileCountdownOutput"); 
    const button = document.getElementById("whileCountdownButton");

    if (output.textContent === "") {
        let i = 10;
        while (i >= 0) {
            const para = document.createElement("p");
            const output = document.getElementById("whileCountdownOutput");        
    
            if (i === 10) {
                para.textContent = `Countdown ${i}`;
            } else if (i === 0) {
                para.textContent = "Blast off!";
            } else {
                para.textContent = i;
            }
    
            output.appendChild(para);
            i--;
        }
        button.textContent = "Close countdown";
    } else {
        output.textContent = "";
        button.textContent = "Start countdown";
    }
}

const whileCountdownButton = document.getElementById("whileCountdownButton");
whileCountdownButton.addEventListener("click", whileCountdown);
Using do...while
HTML codes
<button id="dowhileCountdownButton">Start countdown</button>
<div id="dowhileCountdownOutput"></div> 
JS codes (countdown_dowhile.js)
function dowhileCountdown () {
    const output = document.getElementById("dowhileCountdownOutput"); 
    const button = document.getElementById("dowhileCountdownButton");

    if (output.textContent === "") {
        let i = 10;
        do {
            const para = document.createElement("p");
            const output = document.getElementById("dowhileCountdownOutput");        
    
            if (i === 10) {
                para.textContent = `Countdown ${i}`;
            } else if (i === 0) {
                para.textContent = "Blast off!";
            } else {
                para.textContent = i;
            }
    
            output.appendChild(para);
            i--;
        } while (i >= 0);
        button.textContent = "Close countdown";
    } else {
        output.textContent = "";
        button.textContent = "Start countdown";
    }
}

const dowhileCountdownButton = document.getElementById("dowhileCountdownButton");
dowhileCountdownButton.addEventListener("click", dowhileCountdown);

Guest List

Task: Create guest list by registration, with exception
MDN: Looping code: Active learning: Filling in a guest list
The original task is more simple, however I want to exercise these as well:
  • HTML form
  • Webpage output
  • DOM manipulation (creating list elements)
Using for loop, lists displayed as joined string.
Guest Registration

Note for Phil and Lola: see Admin directly.

HTML codes
<h5>Guest Registration</h5>
<p>Note for Phil and Lola: see Admin directly.</p>
<label for="guestInput">Guest name:</label>
<input id="guestInput" type="text">
<button id="guestButton">Register</button>
<p id="guestComment"></p>
<p id="guestOutput"></p>
<p id="rejectOutput"></p>
JS codes (guestlist_para.js)
const guestList = [];
const rejectList = [];

function processGuest () {  
    const guestInput = document.getElementById("guestInput");
    const comment = document.getElementById("guestComment");
    const guestOutput = document.getElementById("guestOutput");
    const rejectOutput = document.getElementById("rejectOutput");

    let newApplicant = guestInput.value;
    newApplicant = newApplicant.trim();
    newApplicant = newApplicant.toLowerCase();
    newApplicant = newApplicant[0].toUpperCase() + newApplicant.slice(1);

    guestInput.value = "";
    guestInput.focus();
    comment.textContent = "";

    if ((newApplicant === "Lola") || (newApplicant === "Phil")) {
        let addReject = true;
        comment.textContent = `Sorry, ${newApplicant}, please see Admin to register.`;
        for (reject of rejectList) {
            if (newApplicant === reject) {
                addReject = false;
                break;
            }
        }
        if (addReject) {
            rejectList[rejectList.length] = newApplicant;
        }
    } else {
        let addGuest = true;
        for (guest of guestList) {
            if (newApplicant === guest) {
                comment.textContent = `Sorry, ${newApplicant}. That name has been registered.`;
                addGuest = false;
                break;
            }
        }
        if (addGuest) {
            guestList[guestList.length] = newApplicant;        
            comment.textContent = `Hello, ${newApplicant}! Your request is approved.`;
        }
    }

    if (guestList.length !== 0) {
        guestList.sort();
        guestOutput.textContent = `Registered guests: `
        for (let i = 0; i < guestList.length; i++) {
            if (i === 0) {
                guestOutput.textContent += guestList[i];
            } else if (i === (guestList.length - 1)) {
                if (guestList.length === 2) {
                    guestOutput.textContent += ` and ${guestList[i]}.`;
                } else {
                    guestOutput.textContent += `, and ${guestList[i]}.`;
                }
            } else {
                guestOutput.textContent += `, ${guestList[i]}`;
            }
        }
    }

    if (rejectList.length !== 0) {
        rejectList.sort();
        rejectOutput.textContent = `Please see Admin: `
        for (let i = 0; i < rejectList.length; i++) {
            if (i === 0) {
                rejectOutput.textContent += rejectList[i];
            } else if (i === (rejectList.length - 1)) {
                if (rejectList.length === 2) {
                    rejectOutput.textContent += ` and ${rejectList[i]}.`;
                } else {
                    rejectOutput.textContent += `, and ${rejectList[i]}.`;
                }
            } else {
                rejectOutput.textContent += `, ${rejectList[i]}`;
            }
        }
    }
}

const guestButton = document.getElementById("guestButton");
guestButton.addEventListener("click", processGuest);
Using for loop, lists displayed as numbered list.
Guest Registration

Note for Phil and Lola: see Admin directly.

HTML codes
<h5>Guest Registration</h5>
<p>Note for Phil and Lola: see Admin directly.</p>
<label for="guestInput2">Guest name:</label>
<input id="guestInput2" type="text">
<button id="guestButton2">Register</button>
<p id="guestComment2"></p>
<div id="guestOutput2"></div>
<div id="rejectOutput2"></div>
JS codes (guestlist_ol.js)
const guestList2 = [];
const rejectList2 = [];

function processGuest2 () {  
    const guestInput2 = document.getElementById("guestInput2");
    const comment = document.getElementById("guestComment2");
    const guestOutput2 = document.getElementById("guestOutput2");
    const rejectOutput2 = document.getElementById("rejectOutput2");

    let newApplicant = guestInput2.value;
    newApplicant = newApplicant.trim();
    newApplicant = newApplicant.toLowerCase();
    newApplicant = newApplicant[0].toUpperCase() + newApplicant.slice(1);

    guestInput2.value = "";
    guestInput2.focus();
    comment.textContent = "";

    if ((newApplicant === "Lola") || (newApplicant === "Phil")) {
        let addReject = true;
        comment.textContent = `Sorry, ${newApplicant}, please see Admin to register.`;
        for (reject of rejectList2) {
            if (newApplicant === reject) {
                addReject = false;
                break;
            }
        }
        if (addReject) {
            rejectList2[rejectList2.length] = newApplicant;

            if (rejectList2.length === 1) {
                rejectOutput2.textContent = "Please see Admin:"

                const newOl = document.createElement("ol");
                newOl.setAttribute("id", "rejectOl");
                rejectOutput2.appendChild(newOl);
            }

            const newLi = document.createElement("li");
            newLi.textContent = rejectList2[rejectList2.length - 1];

            const rejectOl = document.getElementById("rejectOl");
            rejectOl.appendChild(newLi);
        }

    } else {
        let addGuest = true;
        for (guest of guestList2) {
            if (newApplicant === guest) {
                comment.textContent = `Sorry, ${newApplicant}. That name has been registered.`;
                addGuest = false;
                break;
            }
        }
        if (addGuest) {
            guestList2[guestList2.length] = newApplicant;        
            comment.textContent = `Hello, ${newApplicant}! Your request is approved.`;

            if (guestList2.length === 1) {
                guestOutput2.textContent = "Registered guests:"

                const newOl = document.createElement("ol");
                newOl.setAttribute("id", "guestOl");
                guestOutput2.appendChild(newOl);
            }

            const newLi = document.createElement("li");
            newLi.textContent = guestList2[guestList2.length - 1];

            const guestOl = document.getElementById("guestOl");
            guestOl.appendChild(newLi);
        }
    }


}

const guestButton2 = document.getElementById("guestButton2");
guestButton2.addEventListener("click", processGuest2);

List elements

Task: Create list elements for array members
MDN: Test your skills: Loops: Loops 1 - Create bulleted list
Additional study area: DOM manipulation
MDN: DOM manipulation
Exercise page
HTML codes
<body>
    <section class="preview">
    </section>
</body>
JS codes
<script>
    const myArray = ['tomatoes', 'chick peas', 'onions', 'rice', 'black beans'];
    const list = document.createElement('ul');

    // Add your code here

    for (item of myArray) {
        const listItem = document.createElement("li");
        listItem.textContent = item;
        list.appendChild(listItem);
    }

    // Don't edit the code below here!

    const section = document.querySelector('section');
    section.appendChild(list);
</script>

Phone book

Task: Create phone book look up
MDN: Test your skills: Loops 2: Phonebook
Using break to exercise it. As consequence though, the code can only display the first contact found.
Additional study area: Array of objects
MDN: JavaScript object basics
Exercise page
HTML codes
<body>
    <section class="preview">
    </section>
</body>
JS codes
<script>
    const name = 'Mustafa';
    const para = document.createElement('p');

    const phonebook = [
        { name : 'Chris', number : '1549' },
        { name : 'Li Kang', number : '9634' },
        { name : 'Anne', number : '9065' },
        { name : 'Francesca', number : '3001' },
        { name : 'Mustafa', number : '6888' },
        { name : 'Tina', number : '4312' },
        { name : 'Bert', number : '7780' },
        { name : 'Jada', number : '2282' },
    ]

    // Add your code here

    for (contact of phonebook) {
        if (contact.name === name) {
            para.textContent = contact.number;
            break;
        }
    }

    // Don't edit the code below here!
    const section = document.querySelector('section');
    section.appendChild(para);
</script>

isPrime

Task: isPrime game
MDN: Test your skills: Loops 3: isPrime
Exercise page
HTML codes
<body>
    <section class="preview">
    </section>
</body>
JS codes
<script>
    let i = 500;
    const para = document.createElement('p');

    function isPrime(num) {
    for(let i = 2; i < num; i++) {
        if(num % i === 0) {
        return false;
        }
    }

    return true;
    }

    // Add your code here
    let j = 500;

    for (let j = 500; j > 1; j--) {
        if (isPrime(j)) {
            if (para.textContent === "") {
                para.textContent += `Prime numbers from 500 to 1 are: ${j}`;
            } else {
                para.textContent += `, ${j}`;
            }            
        };
    }

    // Don't edit the code below here!
    const section = document.querySelector('section');
    section.appendChild(para);
</script>

Prime List

Task: Get input integer grater than 1, list all primes up to that number
Javascript.info: While-for: Output prime numbers
Exercise page

HTML codes
<label for="primeListInput">Enter a number: </label>
<input id="primeListInput" type="text">
<button id="primeListButton">List Prime</button>
<p id="primeListOutput"></p>
JS codes: primeList.js
function listPrime () {
    const primeListInput = document.getElementById("primeListInput");
    const max = primeListInput.value;

    const output = document.getElementById("primeListOutput");
    output.textContent = "";

    primeListInput.value = "";
    primeListInput.focus();

    // assuming numbered entered is an integer >= 2

    number: for (let n = 2; n <= max; n++) {
        for (let i = 2; i < n; i++) {
            if (n % i === 0) continue number;
        }
        output.textContent += n + " ";
    }
}

const primeListButton = document.getElementById ("primeListButton");
primeListButton.addEventListener("click", listPrime)

template

Task: Create ...
MDN: Test your skills: Loops: template
Additional study area: ...
MDN:
Exercise page
HTML codes
<body>
    template
</body>
JS codes
<script>
    template
</script>

References