Exercise

Let’s conclude this section by solidifying our knowledge of arrays with a quick exercise making use of what we have learned so far about the power of arrays:

  • Start by opening up Google Chrome and heading over to the console tab in inspector tools.
  • Now create an array of your favourite films.
  • Change the second to last item in your array to a different value.
  • Now remove the first item in your array but save the value to a variable
  • Sort the array reverse-alphabetically.
  • Find out the size of your array and assign that value to a variable.
  • Now log the following statement to the console, replacing the square brackets with actual data from the array: ‘This is my array of my favourite things [List array of things separated by ’ – ‘]. There are [size of array] items in my array, and I just removed [Removed value] from the list’.

Loops

We have just explored arrays and their uses. We looked at examples of shopping lists and lists of favourite things. We also looked at retrieving that information back out of arrays and assigning it to a variable. This is useful for individual elements, but what about when we are working with large arrays with lots of data? Imagine for a second that we have a huge list of people’s dates of birth and from that list, we wanted to create a new list of people’s ages. If we had five elements in that array, we could easily retrieve each of these elements, work out their age from their date of birth, then add that age to a new array. For five elements this might not take too long. Now what would you do if we have 500 elements in an array? You might want to find a way to speed that process up. What if we could write some code that would automatically sort through an entire array and perform a specified action on each individual item inside it? All by running one single command? Or what if you have an array of objects that contains all of your navigation bar’s titles and destination links, which you need to iterate through and output to the webpage? Ladies and gentlemen, I give you ‘loops’, and with loops I also present to you the power of programming as a huge time-saver and the height of convenience. You are about to see why programming really is so powerful.

The loops

As we just discovered, loops are a way of performing an action multiple times in a programmatic way. They are a way to run a piece of code multiple times as per your requirements. They are often used alongside arrays, but their uses span far beyond just working with arrays. There are four different types of loops in JavaScript. The most common loop you will see is the ‘for loop’. Let’s take a closer look at this loop now.

The for loop

The for loop is a very common loop, which simply runs a section of code a defined number of times. Here’s how it works: