CPNT 262 Day 8 - Looping and higher order functions

Housekeeping

  • Don't forget to vote!

Trophy of the day


1. Spoiler Demos

  • add validation to your Tip Calculator that ensures that:
    1. Remove the required attribute from total field so we can test;
    2. The user entered a number for Bill Total (i.e. not empty);
    3. The entered Bill Total is greater than $0;
    4. Throw an error if total is negative or missing.
  • Text area character counter

2. Arrays

Materials


3. Loops with Array.prototype.forEach()

Materials

Key Takeaways

  • item is the conventional name given to the array item passed to the callback function but you can name it whatever you want (i.e. noun if you're looping an array of nouns).
  • You can optionally add the index (of the current iteration) as a second argument to the callback function.

Activities


4. Addition assignment operator +=

Terminology

Append
To add to the end of a string or list.

Materials

Key Takeaways

  • The addition assignment operator += is used to add a string to the end of a variable

    const sentence = "This is a ";
    sentence += 'sentence.';
    console.log(sentence); // "This is a sentence."
  • The addition assignment operator += is a shortcut for the following:

    const sentence = "This is a ";
    sentence = sentence + 'sentence.';
    console.log(sentence); // "This is a sentence."
  • Addition assignment is often used to gradually add to an output variable from within a loop

    let output;
    const list = document.querySelector('ul');
    const hobbies = ['pinball', 'bug hunting', `netflix`];

    const handleItem = function(item) {
    output += `<li>${item}</li>`;
    }
    hobbies.forEach(handleItem);

    list.innerHTML = output;

Lab Time

Stretch Activities


Prep

Arrays

Loops

Manipulating Documents