Lesson 13: Introduction to Arrays
Overview
This lesson introduces arrays as a means of storing lists of information within a program. The class begins by highlighting the difficulties that arise when trying to store lists of information in a variable. Students then watch a short video introducing arrays and a subset of the operations that can be performed with them. Students will work in Code Studio for the remainder of the class as they practice using arrays in their programs. At the conclusion of the sequence, students build a simple app which can be used to store and cycle through a list of their favorite things. In the next lesson, students will continue working with a version of this app that can display images and not just text strings.
Purpose
Some sort of list data structure is a component of almost all programming languages. A list allows large amounts of information to be easily referenced and passed around a program, and the use of a numeric index allows individual items in a list to be accessed. Historically a list would have literally been a single contiguous chunk of memory and the index or address was used to know how far into that chunk a relevant piece of information was stored. In many modern languages, however, it is more likely that the items in an array are stored at many locations on your computer’s hard drive, and the index is only useful to help the programmer identify different components. In this way, a JavaScript array is actually another example of abstraction. We know that it is holding a list of related information, but we don’t need to think about the actual implementation details.
Agenda
Getting Started
Activity
Wrap-up
Extended Learning
View on Code Studio
Objectives
Students will be able to:
- Identify an array as a data structure used to store lists of information in programs.
- Create arrays and access information stored within them using an index.
- Manipulate an array using the append, insert, and remove operations.
- Account for the fact that JavaScript arrays are zero-indexed when using them in a program.
Vocabulary
- Array - A data structure in JavaScript used to represent a list.
- List - A generic term for a programming data structure that holds multiple items.
Introduced Code
Teaching Guide
Getting Started
Prompt: What makes lists useful in everyday life?
Goal
Demonstrate that lists are a desirable feature of a programming language and that using variables to store lists is cumbersome or impossible. Motivate the need for arrays.
Thinking Prompt:
- "Today we’re going to start looking at how we can use lists in programs, but before we dive into that, let’s think about why we would want to in the first place. What are the benefits of creating lists? Why is it helpful to keep information in lists?"
Discuss:
Students may discuss in small groups or you can just ask for ideas from the class. Potential answers include:
- Lists help us organize information.
- Lists help us collect all the relevant information in one place.
- Lists show that a lot of ideas are related.
- Lists help us order or prioritize ideas.
- Lists help us think about the big picture.
Transition: Variables are a bad way to store lists.
Transitional Remarks
There are a lot of benefits to keeping lists of information in real life. Since we use programming to solve a lot of similar problems, we would like to keep lists of information in our programs, too.
Right now, the only way we know how to store information in our programs is with a variable, but each variable can only store a single piece of information.
Today we’ll be learning about a new programming construct that will allow us to hold as many pieces of information as we want within a single list.
Activity
App Lab: Introduction to Arrays
This set of levels looks long, but all the problems are relatively short and small.
You might consider watching the first video as a whole class before diving in.
Wrap-up
Reflection: When to use a variable and when to use an array
Goal: Students now know how to store information in both variables and arrays. Help students synthesize their new knowledge by trying to develop a rule for when to use a variable vs. an array. This is also just a useful way to assess students’ understanding of arrays at the conclusion of the lesson.
Thinking Prompt (Also in Code Studio)
-
Your app needs to store the following information. Decide whether you would use an array or a variable to store it?
- All the messages a user has sent
- The highest score a user has ever reached on the app
- A username and password to unlock the app
-
In general, when do you think you should you store information in an array, and when should you use a variable?
Discuss: You can use these questions as an exit ticket, but it is probably even more useful to discuss as a class. Use this discussion to possibly identify and address any misconceptions about what an array is and how it stores information. Here are some key points to pull out:
- Variables store single pieces of information, while arrays store many.
- An array can grow in size to accommodate more information.
- Arrays are slightly more complex to use than variables. If you are only going to be storing a small and fixed amount of information, it is probably appropriate to use multiple variables.
Conclusion:
Remarks
We are going to keep exploring arrays in the coming lessons. Keep your eye out for some of the distinctions we just discussed, and keep thinking about how you might want to use arrays in applications of your own.
Extended Learning
One of the last levels in App Lab challenges students to keep developing the app. If you wish, you may also have students submit these projects.
- Lesson Vocabulary & Resources
- 1
Student Instructions
Unit 5: Lesson 13 - Introduction to Arrays
Background
It is very common to want to store lists of information in our programs. This could be done with variables but they have many shortcomings when it comes to doing so. Most programming languages, including JavaScript, include a list structure of some sort to make it easier to hold many pieces of related information. When used carefully, lists can greatly expand the functionality of our apps. The list structure in JavaScript is called an array.
Vocabulary
- List: A generic term for a programming data structure that holds multiple items.
- Array: A data structure in JavaScript used to represent a list.
Lesson
- Learn how to design arrays to hold a variety of information.
- Access information in an array by its index.
- Develop a simple application that uses an array.
Resources
- Tutorial Video: Introduction to Lists
- Introduction to Lists - Part 1
- 2
Student Instructions
Creating an Array
Arrays have many features which make them different from variables, but most of what you've learned about variables also applies to arrays. For example, just like a variable:
- Arrays should be given a descriptive and meaningful name.
- Arrays are created using
var
. - Arrays can be initialized/set using
=
.
Example: Creating an Array
This array contains 3 values: 100, 250, 500. Notice that the values are separated with commas ,
and that the entire array is enclosed in brackets [ ]
. We can use console.log
to display the contents of an array just like we would a variable.
Do This:
- Following the format described above create an array which contains the even numbers from 0 to 10.
- Make sure your array has a descriptive and meaningful name.
- Use
console.log
to display the contents of your array. Below is an example of the output your program should generate.
Student Instructions
Adding Items to an Array
In our last exercise we created our array and initialized it with some values. Another way to do this is to add items to your array on separate lines. The simplest way to do this is to add a new item to the end of your array using the appendItem
command.
To append means to add or to join. When you append an item to an array you actually add a new location to the end of the array that contains the new value, so that the total size of the array grows by one. Since you can always add items to an array after creating it, it is very common to create an empty array and then add values in subsequent portions of your program.
Do This:
- Read the documentation for
appendItem
. - Create an empty array called
oddNumbers
. - Use
appendItem
to add the odd numbers 1-11 to your array.
- Use
console.log
to confirm your array is holding the correct values. The output should look like the example below.
- Introduction to Lists - Part 2
- 5
Student Instructions
Accessing Items in an Array
An array is comprised of many locations. You can individually set or reference the information at each location of your array just like a variable. To tell your locations apart each has a separate number, or index, that identifies it.
Arrays in JavaScript are zero-indexed which means the first index is 0. This is similar to binary number systems which begin counting at 0. For example an array of 10 items would have indexes 0-9. As a result the last index is always one less than the length of the array.
Accessing Array Items by Index: If you know the index of the item you wish to access you can reference it using square brackets list[index]
. The example below prints the value of the 4th element in the array.
Do This:
Starter code has been provided which creates an array of the numbers 1 through 10
- Use
console.log
to display the first item in your array. - Use
console.log
to display the last item in your array. - Use
console.log
to display the number 5 from the array.
Student Instructions
Index Practice
It will take some practice to get comfortable using array indexes. We'll do a couple of exercises to build your confidence.
Do This:
Starter code has been provided that creates an array called myNumbers
.
- Use
console.log
and array indexes to write the contents ofmyNumbers
to the screen in order, as shown to the right. Your commands should be of the formconsole.log(myNumbers[index])
.
- Introduction to Lists - Part 3
- 8
Student Instructions
Setting Values by Index
Each location in an array can be treated like its own variable. We've already seen how we can use bracket notation to reference values stored at specific locations in an array. Just like with variables, we can assign the value of a specific location in an array using =
(the assignment operator).
Example: The value at index 0 of this array is set to 10.
Do This:
Starter code is provided that creates an array of 0's and 1's. Set all the values in this array to be 0.
- Use indexes and the assignment operator
=
to set all the 1's to be 0. - Check the output of the
console.log
to confirm the array only contains 0's. Example shown on the right.
Student Instructions
Array Values: Arithmetic
You can reference locations in arrays in arithmetic expressions, just like you might a variable.
The starter code creates an empty array and adds three random values to it.
You will be adding code to your program that calculates the sum of the values in the array.
Notice the difference between displaying an array as part of a string or by itself. Example:
- code:
console.log(myNumbers)
displays with brackets as:[1, 2, 3, 4]
- code:
console.log("my list: "+myNumbers)
displays without brackets as:my list: 1, 2, 3, 4
So when it's part of a string it does not print the square brackets around the ends of the list. This is a "feature" of the language with no great explanation. In the first case it sees only a list and it produces a more technical representation. In the second case the system is trying hard to convert the list to a nice looking string.
Do This:
- Add a variable to your program to hold the sum of the array values.
- Assign the value of the variable to the sum of the three array values.
- Use
console.log
to confirm that you have correctly calculated the sum of the values. Below is sample output from one run of the program.
Student Instructions
Reassigning Array Values
We've already seen many examples of how a location in an array can be treated identically to a variable. The last exercise we'll perform to prove this point is reassigning array values. The syntax for reassigning values stored in an array is identical to that used when reassigning variables. Even the ++
notation to increase a value by one works!
The program you're about to see creates an empty array and adds three random values to it. You will be adding code to the program that increases each value by one.
Do This:
- Add code to the program that increases the value stored at each location in the array by one.
- Use
console.log
to confirm that you have correctly increased the values. Below is sample output from one run of the program.
Student Instructions
Arrays Can Hold Strings
So far we have been using arrays to hold numbers, but each location in an array could hold a string instead.
Note: It is possible for an array to hold both strings and numbers, but typically you will only want your arrays to hold one type of data.
Do This:
- Create an empty array.
- Use
appendItem
to individually add strings to your array, forming a sentence of at least 5 words. - Use
console.log
to confirm you succesfully created your sentence.
Student Instructions
Inserting Items: Array Indexes
If you want to add elements in the middle of your array you can use insertItem
to specify an index at which an item should be inserted.
Just like appendItem
, insertItem
creates a new location in the array. However insertItem
allows you to insert an item anywhere in the array, not just at the end, and it shifts all elements at or after its index one location over.
Do This:
- Read the documentation for
insertItem
. - Starter code has been provided which appends some strings to an array, but right now they don't form a complete sentence.
- Use
insertItem
to individually insert strings to your array to form a complete sentence. - Use
console.log
to confirm you succesfully created your sentence.
Student Instructions
Removing Items
Sometimes we want to remove something from an array. In order to do so you'll need to specify the index of the item that should be removed.
Note: removeItem
removes the location in the array at the index provided. As a result the array is one location shorter and all the indexes after the index provided will have their index decreased by one.
Do This:
- Read the documentation for
removeItem
. - Starter code has been provided which creates an array of strings.
- Use
removeItem
to individually remove all the "REMOVE" strings in your array to form a complete sentence. - Use
console.log
to confirm you succesfully created your sentence.
Note: Keep an eye out; your indexes will shift as you remove items.
Student Instructions
Out of Bounds
In many languages trying to access indexes of an array that don't exist will create an error. JavaScript allows for some strange behavior with arrays that it's useful to see, even though you will likely never use this functionality.
Warning: some of this code will generate errors or work in unexpected ways. Don't spend a long time trying to understand weird results. The point to take from this is referencing indexes that are out of bounds will almost never do what you intend, and we'll be learning ways to avoid this as we move forward.
Do This:
- Starter code has been provided which creates an array with three elements.
- Uncomment the first command that references indexes that are out of bounds and run the code.
- Examine the output and try to understand what is happening.
- Reset and then recomment the line after you've used it.
- Repeat the process for all the lines.
Note: We have used a different style of comment in this program. * long block comment */
is used when you want to write a multiple-line comment.
- Introduction to Lists - Part 4
- 16
Student Instructions
Array.length
As we saw in the last exercise, there are many strange behaviors that can result from referencing array indexes that are less than 0 or greater than the highest index in your array. If you want to avoid these kinds of errors then it is useful to know how long your array is, especially since we've seen that arrays can grow and shrink during the course of our program.
You can always check the current length of your array using the command list.length
where "list" is the name of your array. It evaluates to a number indicating how many items are in your array.
Do This:
- Starter code has been provided which creates several long arrays.
- Use
list.length
andconsole.log
to determine how many items are in each array. An example of the output is below.
Student Instructions
Expressions as Indexes: list.length - 1
We have been accessing information in an array by using numbers, but we can actually use any expression that evaluates to a number as an index in our array. The first example of this we will explore is accessing the last item in our array.
Arrays are zero-indexed, which means that the first index is 0. Therefore an array with a length of 3 will have indexes 0, 1, and 2. Notice that the last index is 1 less than the length. This will always be the case, and so we can use this expression to access the last element in any array:
Do This:
- Starter code has been provided that which creates several arrays.
- Use the syntax provided above and
console.log
to display the final item in each list.
Student Instructions
Expressions as Indexes: Using Variables
We can use any expression that evaluates to a number as an index in an array. Here are some examples:
Do This:
- Starter code has been provided which creates an array of colors.
- Write code that logs a random color from this list to the console by generating a value for a random index. Try to write your program using
list.length
rather than hard-coding the length of the list.
- "My Favorite Things" Demo App
- 20
Student Instructions
My Favorite Things
Check out this simple app for creating a collection of your favorite things. We're going to be working towards building this app over the next several exercises. As you might expect, this application uses an array to store and organize information.
Do This:
- Use the "My Favorite Things" app and try to predict how arrays are used to create the functionality you observe.
- Some features to notice:
- The app keeps track of a list of your favorite things.
- You may use buttons to move forward and backward through your list.
- The current entry and total number of entries are indicated at the top.
- You may add a new entry at the current location in your list.
Student Instructions
Getting Started: Creating IDs
To get your application off the ground we've provided the user interface elements that you will use in your application. Unfortunately they all currently have default IDs which don't reflect how the elements will be used.
Do This:
- Create a descriptive and meaningful ID for each element in your app.
Student Instructions
Create Your Array
Now that we've dealt with our design elements we'll need to start writing the actual code of our app. This app keeps track of a list of items, so we know that we'll need to create an array to store them.
Do This:
- Create an array that will hold your list of favorite things.
- Add three of your own favorite things to your array.
Student Instructions
Displaying Information to the User
Before we make our application interactive, we'll want to practice creating some simple user output. When the app starts up, the first item in your list should be displayed. Let's write the code that will display this information to the screen.
Do This:
- Using
setText
set the main text area to show your first favorite thing. - Using
setText
andlist.length
set the text indicating what item of the list the user is currently viewing.- Hint: since arrays are zero-indexed you will have to add one to your index to generate the correct value to display. For now you can just write in a
1
and worry about making it change later.
- Hint: since arrays are zero-indexed you will have to add one to your index to generate the correct value to display. For now you can just write in a
- Note: neither of these outputs will be able to change yet. Don't worry, we'll be taking care of that in coming exercises!
Student Instructions
Current Index
This app also allows a user to scroll through individual items in the array. In order to keep track of which index we are currently viewing, our application will need a global variable that stores the current index. In coming exercises we'll want our global index to change, so let's make sure that your code references your global index rather than fixed values.
Do This:
- Create a global variable that will be used to keep track of the current index in the array. Set this variable to 0.
- Update
setText
which displays the words to show your first favorite thing using the global index variable instead of a hard-coded number. - Update
setText
which displays the current item number to use the global index variable instead of a hard-coded number.- Hint: since arrays are zero-indexed you will have to add one to your index to generate the correct value to display.
- Note: neither of these outputs will be able to change yet. Don't worry, we'll be taking care of that in coming exercises!
Student Instructions
Next Button
Nice work! Your application should now have some simple output displaying one of your favorite things and indicating which item of your list you are showing. To make things more interesting, however, we want to be able to change which item we display.
To change the item displayed, the user will use the "Next" and "Last" buttons. These should increase or decrease the global index by one and then you should update the information displayed on the screen. To start out with, however, we'll just be writing code for our Next Button.
Do This:
- Add an event handler to the "Next" button.
- Write code in this event handler that increments your global index variable and then updates the output on the screen.
- Note: If your code from the last exercise was written to reference this variable then you should just be able to reuse it once you've incremented your variable. We'll talk more about this in the next exercise.
- Run your program to confirm that the user can move forward through the list and that the output displayed is correct.
- Note: You may notice that your program throws an error if the global index variable goes out of bounds. Don't worry about this for now - we'll fix it in a later exercise.
Student Instructions
Last Button
Our user can now move forward through our list of favorite things, and we're about to write code that allows them to move backwards as well. If you've written your code to reference your global index then this should only require you to decrease its value by one and reuse code that updates the screen output. Before we write the code for backwards let's work on cleaning up our code.
Removing Repeated Code: Once you add the code for moving backwards through your array, your program will have three places where it updates the screen by setting the text of your screen elements. Rather than repeating this code we should create a function that updates the screen and then call it every time we need to refresh those elements. This will not only make our program easier to read and avoids the errors that can arise from redundant code, but it also makes it easier to make changes to how our program runs, since all the code that updates the screen is in a single place.
Do This:
- Write a function that contains the
setText
commands you have used to update the screen. - Replace the places in your code where you used to have these commands with calls to your new function.
- Add an event handler to the "Last" button that decreases the global index variable by one and then updates the screen by calling your new function.
- Run your program to confirm that the user can move forward AND backward through the list and that the output displayed is correct.
- Note: You may notice that your program throws an error if the global index variable goes out of bounds. Don't worry about this for now - we'll fix it in a later exercise.
Student Instructions
Adding New Items
Now we want our user to be able to add items of their own to the list. As you might have guessed, this is as easy as inserting an item into our array at the current index.
Do This:
- Add an event handler to the "Add" button.
- Write code in your event handler that:
- Uses
getText
to access the user's new item. - Uses
insertItem
to add that item to your array at the current index. - Calls your update function to update the screen (the new item should be displayed).
- Uses
- Run your program to confirm that the user can add items to the list and that the output displayed is correct.
Student Instructions
if Statements: Staying in Bounds
Currently the user can increase or decrease the value in the global index past the bounds of your array. As a result you've probably already seen that errors are generated.
To prevent this from happening, we're going to add if
statements to the event handlers on the "Next" and "Last" buttons. They should check the value of the global index variable before changing it. If the user is about to step out of the bounds of your array they should either:
- Block: Do not change the index if it will result in a value that is out of bounds.
- Wrap: Set the index to be the other end of the array. In other words, going past the end of the array moves the index back to 0 and going past the beginning of the array sets the index to the last in the array (
list.length
will be helpful here).
Do This:
- Add
if
statements to the event handlers on the "Next" and "Last" buttons that prevent the global index from going out of bounds using one of the two strategies described above. - Run your program to confirm that the user cannot go out of bounds and that the output displayed is correct.
Student Instructions
Keep Going!
Your app should now be fully functional - nice job! There are of course plenty of new pieces of functionality to add. If you have time feel free to make any improvements you wish. Here are some ideas:
- Allow the user to append items rather than add them at the current location.
- Give the user the ability to remove the item at the current index. This can be a little tricky if you remove the item at the end of the list so see if you can account for that.
- Only add words if they are not blank.
- Improve the appearance of the app.
Student Instructions
Choose: Array or Variable?
Your app needs to store the following information. For each type of information, decide whether you would use an array or a variable to store it:
- All the messages a user has sent
- The highest score a user has ever reached on the app
- A username and password to unlock the app
Student Instructions
Free Response: Choosing Array or Variable
In general, when do you think you should store information in an array, and when should you use a variable?
Standards Alignment
View full course alignment
Computer Science Principles
1.1 - Creative development can be an essential process for creating computational artifacts.
1.1.1 - Apply a creative development process when creating computational artifacts. [P2]
- 1.1.1B - Creating computational artifacts employs an iterative and often exploratory process to translate ideas into tangible form.
5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
5.1.2 - Develop a correct program to solve problems. [P2]
- 5.1.2A - An iterative process of program development helps in developing a correct program to solve problems.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
- 5.3.1A - Procedures are reusable programming abstractions.
- 5.3.1B - A function is a named grouping of programming instructions.
- 5.3.1C - Procedures reduce the complexity of writing and maintaining programs.
- 5.3.1K - Lists and list operations, such as add, remove, and search, are common in many programs.
- 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
5.5 - Programming uses mathematical and logical concepts.
5.5.1 - Employ appropriate mathematical and logical concepts in programming. [P1]
- 5.5.1H - Computational methods may use lists and collections to solve problems.
- 5.5.1I - Lists and other collections can be treated as abstract data types (ADTs) in developing programs.
- 5.5.1J - Basic operations on collections include adding elements, removing elements, iterating over all elements, and determining whether an element is in a collection.