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:
- Remove the
required
attribute fromtotal
field so we can test; - The user entered a number for Bill Total (i.e. not empty);
- The entered Bill Total is greater than $0;
- Throw an error if
total
is negative or missing.
- Remove the
- Text area character counter
2. Arrays
Materials
- MDN: Arrays
- MDN: Common Array Operations
- Takeaways: Array fundamentals
3. Loops with Array.prototype.forEach()
Materials
- Looping code
Array.prototype.forEach()
- Video: JavaScript Array forEach Method by Steve Griffith
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 variableconst 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 looplet 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
- Instead of
.innerHTML
, try using one of the following accepted methods of outputting HTML to a page: - Create a function that accepts any array as an argument and returns a random item in that array. See: Find a random item in an Array
Prep
Arrays
Loops
- Looping code
Array.prototype.forEach()
- Video: JavaScript Array forEach Method by Steve Griffith
- Video:
for
Loop by Mosh Hamedani
Manipulating Documents
- Review:
Element.innerHTML
- Reference: Addition assignment (
+=
)