Exercise Monday

Goal: In the Looping lesson, we learned:

  • How to use a forEach() loop
  • Naming conventions for arrays and the parameter in a loop
  • The importance of DRY code

As you saw, loops can be really powerful! They're an incredibly important programming concept, and we'll be using them from here on out. Begin becoming comfortable utilizing loops by completing the exercises listed below. We'll begin with several exercises in the console, and move on to creating and updating small projects.

Warm Up

  • How can loops contribute toward DRY code? Why is DRY code important?
  • If we used forEach() to loop through an array called "kittens", what should we call the parameter in the forEach() function? Why?
  • What does the += operator do?


Looping Practice in the Console

  • Make an array of your friends' names. Loop through it and alert() a greeting to each.
  • Write a loop to multiply an arbitrary amount of numbers. This should look similar to the code to sum numbers from the lesson.

Refactoring Existing Projects with Loops

  • Refactor your Mad Libs page we created in this exercise to use a loop.

  • In the Introduction to jQuery lesson we created a web page that triggered alerts containing information about a particular HTML tag whenever a user clicked on an HTML element. Try to refactor this page's multiple, similar event listeners using a loop.

Webpages with Looping

  • Make a web page that lists out your favorite ice cream flavors. Rather than writing the flavors in the HTML, use a JavaScript loop to insert the flavors into the page from an array.

Additional Information

Remember: When choosing a name for the variables in your loop, remember that it is good practice to use a plural for the array and the singular form of that word for the loop.

> const languages = ['HTML', 'CSS', 'JavaScript'];
> languages.forEach(function(language) {
    alert('I love ' + language + '!');

The array is named languages and the parameter is the singular language.