13. JavaScript: Arrays & Loops

13. JavaScript: Arrays & Loops

Welcome to Arrays!

šŸŽÆ Learning Goals

  • Understand what an array is and why they are useful
  • Use JavaScript syntax to declare and modify an array

šŸ“— Technical Vocabulary

  • Array
  • Collection
  • Element
  • Index
  • Iterate
  • forEach()
🐚
Here is a sample CodeSandbox for you to fork and use throughout this lesson → Lesson 13: JavaScript: Arrays & Loops
šŸŒ¤ļø
Warm-Up
In a new Sandbox, declare a variable for every scholar in camp. The variable names should be something likeĀ scholar1,Ā scholar2, etc. and the values should be strings of their first names. Be ready to share your code!

Collections

CollectionsĀ are data types that holdĀ multiple thingsĀ - think about your grandma’s cat statue collection - there is probably more than one statue, right?
In JavaScript, there are two types of collections: arrays and objects. In this lesson and during our time at camp, we will mainly focus on arrays.

Arrays

AnĀ arrayĀ is a complex data type. It is an ordered collection that stores multiple values. They are useful whenever you need to keep track of an ordered list of things. This is similar to how we keep track of list items in the real world. Think back to the Warm Up - if there are 15 or 20 scholars in the room, writing out a variable for each one can be time-consuming. An array will allow us to store all scholar names assigned toĀ oneĀ variable!
An array can store any kind of element - from numbers to strings to … other arrays. Usually, a single array holds a lot of items that are all of theĀ same type.
šŸ’­
Think About It
Think about Instagram or TikTok - where might those applications use arrays?
Be ready to share out both the name of the app you are thinking about, and how it might use arrays.

Arrays IRL

It’s very likely that every application you’ve used - on a phone or laptop - utilized arrays in the code that built it.
We can’t see all the code that built every application, but there are some places where it’s very clear that an array would be the best tool to use. Here are some examples from popular sites:
  • InstagramĀ uses arrays to hold all the posts for a given user. Alfie the Alpaca has over 1000 posts, so the array is over 1000 elements long!
  • TwitchĀ has an array of recommended channels. They advertise these channels in the top left corner of their landing page.
  • Playlists on Apple MusicĀ are curated arrays of songs. When a user clicks on the playlist artwork, Apple Music shows them a list of all the songs within that playlist.
notion image

Syntax

An array starts and ends with square brackets:Ā []. Each item inside of the array is called anĀ element. A comma separates each element inside an array. In almost all cases, we will assign the arrays we create to variables.
// An array of strings: var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; // An array of numbers: var durationInSeconds = [238, 243, 200, 173, 214];
We can think of each song as an element in an array:
notion image

Access an Element

Each element in an array is automatically assigned a number called anĀ index. This index can be used to access a specific element inside the array. Indices begin at 0 and count up. If we look back at ourĀ viralHitsĀ array, the following would be true:
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"];
  • Run the World (Girls)Ā has an index of 0
  • Pretty Girl RockĀ has an index of 1
  • FlowersĀ has an index of 2
  • Truth HurtsĀ has an index of 3
  • No Scrubs has an index of 4
By using the square brackets, we can use the index to access a specific value in an array.
Thinking back to the visual representation of our array, here’s the index of each element:
notion image
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; viralHits[0]; //=> "Run the World (Girls)" viralHits[3]; //=> "Truth Hurts"
We can also check how many elements are in an array with theĀ .lengthĀ property:
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; viralHits.length; //=> 5
āœļø
Try-It: Creating Arrays
In the same Sandbox from the Warm Up, create a variable that stores an array of at least 4 strings - you choose what the content is about. The variable name should describe the kind of data those 4 strings hold.
Write a series ofĀ console.log()Ā statements: print out the first element, the last element, and then the second element.

Updating Elements

We can also update elements with the square bracket syntax we looked at earlier. We access the index value that we would like to change and then reassign a new value for that index with aĀ =(the assignment operator).
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; viralHits[1] = "Brave"; console.log(viralHits); //=> ["Run the World (Girls)", "Brave", "Flowers", "Truth Hurts", "No Scrubs"]

Adding Elements

A common way to add something to an already existing array is to use theĀ push()Ā method, which will add an element to the end of the array.
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; viralHits.push("Die For You (Remix)"); console.log(viralHits); //=> ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs", "Die For You (Remix)"]
In the code snippet above,Ā .push()Ā is called on theĀ viralHitsĀ array. We add to the array by givingĀ .push()Ā an argument of the new element we want to add. In this case, it was a new song, the string ofĀ TO THE MOON.

Removing Elements

There are a few ways we can remove elements from an array. Most often, we either want to remove the first or last element. To do this, we have theĀ pop()Ā andĀ shift()Ā methods. Check it out:
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs", "Die For You (Remix)"] viralHits.pop(); console.log(viralHits); //=> ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"
pop()Ā was called on theĀ viralHitsĀ array, and it removed theĀ lastĀ element from the array.
A little different fromĀ .push(),Ā .pop()Ā does not take arguments - it knows what to do: remove the last element from an array.
āœļø
Try-It | Modifying Arrays
For this, you will use the array you wrote in the previous Try It.
Practice accessing specific elements. Make sure toĀ console.log()Ā to verify you are accessing what you think you are.
Now, add two new elements into your array. Use aĀ console.log()Ā to make sure they have been added.
Lastly, remove at least two elements from your array. Again, make sure they have been successfully removed by printing to the console.

Random Elements

Sometimes, we want to pull an element out of an array at random - have any of your teachers ever used popsicle sticks to decide who to call on? That’s a real-life example. We can do the same thing with programming!
JavaScript gives us a tool calledĀ MathĀ to do advanced math, like square roots, logarithms, etc.Ā MathĀ also includes some options for generating random numbers. We’ve got:
  • Math.random()Ā - returns a random decimal between 0 and 1
  • Math.floor(number)Ā - returns the value of a number rounded down to the nearest integer
Let’s work on generating a random number between 0 and 20.
First, generate a random decimal:
var randomDecimal = Math.random(); //=> 0.5617898712887952 (this number will vary)
Now, let’s multiply it by 20:
var randomDecimal = Math.random(); //=> 0.5617898712887952 (this number will vary) var random = randomDecimal * 20; //=> 11.235797425775903
We still don’t have a nice integer as expected, so let’s round it down:
var random = randomDecimal * 20; //=> 11.235797425775903 var final = Math.floor(random); //=> 11
Going back to ā€œwhy would this be usefulā€? A teacher could have a program with an array of names, like this:
var students = ["Leta", "Ellen Mary", "Pam", "Megan", "Amy", "Sarah", "Robyn", "Courtney", "Rachel", "Allison", "Ruby", "Maile", "Julie", "Meg", "Christie", "Emmie", "Aurora", "Tori", "Juliana", "Kerry"];
Now, the teacher can write aĀ pickStudentĀ function:
function pickStudent() { var random = Math.random() * 20; var rounded = Math.floor(random); var student = students[rounded]; // note about how this works below! return student; } var randomStudent = pickStudent(); console.log(randomStudent); //=> one random element from the array will print out
Instead of callingĀ students[0]Ā orĀ students[7], we calledĀ students[rounded]. Since we know thatĀ roundedĀ is a variable that stores a number, the number it stores is substituted in for the variable nameĀ rounded, then the array looks for the element in that index.
šŸ‘„
Discuss
Considering this section on selecting random elements from an array, answer the following questions with your breakout group:
  • What doesĀ Math.random()Ā do?
  • Why did we choose to multiplyĀ Math.random()Ā by 20 for this example?
  • What doesĀ Math.floor()Ā do?
  • Why do we have to pass an argument, or put a number inside the parentheses forĀ Math.floor()?
  • Is it possible for this function to ever return the same number? Why or why not?
šŸ’¼ Takeaways:
  • Math.random()Ā generates a random decimal between 0 and 1. It’s a built-in function of JavaScript
  • We multiplied the result ofĀ Math.random()Ā by 20 for the example above because we wanted to generate a number between 1 and 20. We wanted a number between 1 and 20 because there are 20 elements in the array we are working with
  • We passed an argument toĀ Math.floor()Ā because its job is to round a number down to the nearest whole number. It needs to know which number to round
  • ItĀ isĀ possible for the function to return the same number more than one time

Iteration

Now that you’ve got arrays down, let’s talk about iteration!
šŸŒ¤ļø
What is Iteration?
Iteration (or looping for a specified number of times) is a process of repeating a task for each object in a collection. For each of the scenarios below, we’ll walk through using scenarios we are familiar with to demonstrate the concept.
These are examples that would be programmatically challenging because they would require several steps, but are things that we do every day.
We can also iterate in programming. By ā€œin programming,ā€ we mean things that could be done, with relative ease by a computer, like crunching numbers.
Scenario
Collection
For each...
Do this:
Then:
Grading papers
papers
paper
1. read through it
2. mark the score on the top
3. record score in gradebook
repeat with next paper
Feeding animals
animals
animal
1. bring the animal to the food bucket
2. allow the animal to eat
3. bring animal back to barn
repeat with next animal
Scenario
Collection
For each...
Do this:
Then:
Calculating max heart rate
birth years
year
1. subtract birth year from 2021 to get age
2. subtract age from 220
repeat with next year
Formatting names
names
name
1. capitalize the first letter
2. lowercase all remaining letters
repeat with next name
šŸ’­
Think About It: Iteration in Real Life and Programming
Brainstorm a real-life scenario that uses iteration. Draw a table like the one below in your journal and fill in the blanks.
Column 1
Column 2
Column 3
Column 4
Column 5
Scenario
Collection
For each...
Do this:
Then:
Think of how arrays are used in apps that you use. Why might you a developer to iterate over that collection? Jot it down with a similar table.
Column 1
Column 2
Column 3
Column 4
Column 5
Scenario
Collection
For each...
Do this:
Then:

Iterator Methods

Earlier in the lesson, you learned about the array methodsĀ .push()Ā andĀ .pop(). Now we’re going to learn another array method,Ā .forEach(). It’s what is referred to as an iterator method because its job is to run a function not only once, but one timeĀ for each elementĀ in the array.

forEach

The benefit of iterators is they save us time. When we want to repeat the same thing for a lot of items, we only have to write that command once. For example, if we wanted to do something with each string in theĀ viralHits playlistĀ array, our code would look like this:
var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; console.log(`Have you heard ${viralHits[0]} yet?!`); console.log(`Have you heard ${viralHits[1]} yet?!`); console.log(`Have you heard ${viralHits[2]} yet?!`); console.log(`Have you heard ${viralHits[3]} yet?!`); console.log(`Have you heard ${viralHits[4]} yet?!`);
notion image
Right now, this doesn’t seem so bad, but what if there are 100 songs in that playlist and we wanted to ask if a user had heard each one? That’s a lot of lines of code to write and potentially a lot of places we would need to update it every time we added or removed a song from the playlist.

Syntax

var viralHits = ["Run the World (Girls)", "Pretty Girl Rock", "Flowers", "Truth Hurts", "No Scrubs"]; viralHits.forEach(function(song) { console.log(song); });
Ā 
Let's break this code down.
  • viralHitsĀ is the array we are going to iterate over.
  • .forEach()Ā is a built-in function that runs through each element of the array it’s called on, one-by-one. It takes one argument, a function. This is different from anything we’ve seen before. It’s saying it will run this functionĀ for eachĀ element in the array.
  • function(song) {Ā is the function that will run on each element in the array. If there are 10 elements in the array, it will run 10 times. 100 elements? 100 times.Ā songĀ is the variable that represents the current element in the array being iterated over. song could be named anything, but it is a best practice to relate the variable name to the function’s purpose whenever possible.
  • console.log(song)Ā is the code that will run for each element. In this case, each song’s title in the array will print to the console.
āœļø
Try-It: forEach
In your Sandbox from earlier, write an array with at least four elements, strings, of things you want to learn.
Write aĀ forEachĀ for this array and print out "I want to learn ____" for each element.

Placeholders and Counters

Sometimes, when iterating over an array, our end goal won’t be to do the exact same thing to each element. Sometimes we’ll want to combine elements. Sometimes we’ll want to filter through them and only use some of them.
Here’s a real-life example:Ā Google News has an array of articles related to each term, for example ā€œKode With Klossyā€. When we first search a term, we’ll see all the posts. If we use the filters from the drop-down and select a specific date range, we’ll only see the articles that were posted within the selected range.
How did Google News do that? They iterated over the array ofĀ allĀ articles, checked each one for a piece of criteria, and put those that met the criteria in a placeholder. After it finished iterating, it returned the placeholder and displayed them in the browser.
notion image
Ā 
notion image
Let’s solve a slightly less involved challenge, but one that gets at the same idea. Our goal will be to take an array of numbers and return an array of only the numbers from the original array that are greater than 10. One important thing to know aboutĀ forEachĀ is that it won’t ever change the array it was called on.
// start with an array of numbers var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]; // start a placeholder array that will eventually store numbers over 10 var largeNumbers = []; // iterate over the array numbers.forEach(function(number) { });
In the code above, we set up our placeholder and ourĀ forEach. Now, we need to do some work inside theĀ forEach.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]; var largeNumbers = []; numbers.forEach(function(number) { // check if the current number being iterated over is greater than 10 if (number > 10) { } });
In the code above, we wrote a conditional to check the value of the current number against 10. Now, we need to write code inside that conditional.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]; var largeNumbers = []; numbers.forEach(function(number) { if (number > 10) { // if the number is greater than 10 // push it into the largeNumbers placeholder array largeNumbers.push(number); } });
At this point, ourĀ largeNumbersĀ array is holding all four numbers greater than 10, but we aren’t ever printing it out, so it’s hard to see that.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]; var largeNumbers = []; numbers.forEach(function(number) { if (number > 10) { largeNumbers.push(number); } }); console.log(numbers); // [1, 4, 23, 14, 5, 7, 11, 6, 92] console.log(largeNumbers); // [23, 14, 11, 92]
šŸ“
Try-It: Iteration

🌶 Mild Practices

OPTION 1: Calculate Daily Pay

Trisha gets paid $22 each time she walks a dog. The array below holds 7 numbers, the number of dog walks she took each day last week. Iterate over the array, and print out "Trisha earned $____ today!" for each day.
var dogWalks = [4, 5, 2, 2, 6, 1, 3]

OPTION 2: YELLING

Iterate over an array of strings. For each string, print out the YELLING version of it. Look intoĀ how to convert a string to uppercase!

🌶🌶 Medium Practice

OPTION 1: Sum of All

Write a function that returns the sum of all of the numbers in an array. No empty arrays will be passed in. For example, when an array is passed likeĀ [19, 5, 42, 2, 77], the output should beĀ 145.

OPTION 2: Calculate Total Pay

Trisha gets paid $22 each time she walks a dog. The array below holds 7 numbers, the number of dog walks she took each day last week. Write a function that calculates her total pay.
var dogWalks = [4, 5, 2, 2, 6, 1, 3]

🌶🌶🌶 Spicy Practice

OPTION 1: Sum of Two

Write a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No empty arrays will be passed in. For example, when an array is passed likeĀ [19, 5, 42, 2, 77], the output should beĀ 7.

OPTION 2: Find the Odd (or Even) One Out

Write a function that takes in one argument - an array of numbers. The array must have at least 3 elements. All numbers except for one of them will be either even or odd. You job is to return thatĀ oneĀ number that is the exception. Below are some example inputs and outputs. Make sure your function works on them all.
  • Input:Ā [1, 3, 5, 6], Output:Ā 6
  • Input:Ā [10, 15, 20, 30, 40, 50], Output:Ā 15
  • Input:Ā [19, 5, 42, 1, 77], Output:Ā 42
Ā 
šŸ“
Practice | Arrays & Loops
Declare a variable calledĀ followingĀ that stores an array of your top five favorite accounts to follow on social media, as strings.
  • Change the value of at least one of the elements in the array
  • Add a new account to the array
  • Remove the last account from the array
  • Print the value of the third element of the array
  • Change the value of another element in the array
  • Add another account to the array
  • Print the value of the first element of the array
  • Print one account to the console, at random.
  • Use a forEach loop to print a custom message for each account in your array (e.g., "I love following [account] for daily inspiration!")
Click here for a Spicy Challenge 🌶🌶🌶
Write a function that takes in one argument, a string. If the string is "happy", output a randomly generated sentence about being happy. If the string is "ok", output a randomly generated sentence about being ok. If the string is "sad", output a randomly generated sentence to cheer someone up.Ā You will need to use a function, conditional, multiple arrays, and have to generate a random number.
page icon
For a summary of this lesson, check out the 13. JavaScript: Arrays and Loops One-Pager!