Chapter 8. Arrays: putting data into lists
This chapter covers
- Grouping values as lists
- Creating an array
- Accessing elements in an array
- Manipulating the elements in an array
- Using forEach to visit each element
Almost everything you’ve covered so far has been about organizing your data or organizing your code. This chapter continues that theme but with a twist: it’s not just about grouping items; now you can put them in order.
In The Crypt, you’ll finally have the ability for players to collect items they find on the journey; with arrays they can start on their very own treasure hoards.
Working with lists is an essential part of programming. Blog posts, quiz questions, stock prices, emails, files, tweets, and bank transactions all turn up as lists. In fact, you’ve just read a list of lists! Sometimes the order doesn’t matter and sometimes it does. A list of names could represent the members of a team, with no order, or it could represent places in a race—I’m sure Usain Bolt thinks the order is important there! An ordered list is called an array in JavaScript, as it is in many programming languages.
The items in an array are called its elements and you usually want to work on the elements in some way. You might want to
- Perform some action with each element, say display it on the console or increase it by 20%
- Find only certain elements that match a condition, say all tweets by Lady Gaga, blog posts in a given month, or questions answered correctly
- Combine all the elements into a single value, say to find the total of a list of prices or the average number of points scored per game
The array object in JavaScript provides functions to help you perform all of these actions and more. But, we’re getting ahead of ourselves. Let’s go back to the start and find out how to create an array.
To create an array, use square brackets. Once it’s created, you can assign the array to a variable so you can refer to it in your code. Figure 8.1 illustrates the process.
The following listing creates two arrays and displays them on the console to give this output:
Listing 8.1. Creating arrays (http://jsbin.com/cevodu/edit?js,console)

Commas separate the elements, which can be numbers, strings, objects, functions, or any data type or mix of types—you can even have arrays of arrays. Like the curly braces for objects and the function keyword for functions, the square brackets tell JavaScript to create an array. Once it’s created, you can assign the array to a variable, set it as a property, include it in another array, or pass it to a function.
Listing 8.2 creates a couple of arrays of objects representing places to visit, thisYear and nextYear. Figure 8.2 shows how JS Bin displays the arrays of objects.
Figure 8.2. JS Bin displays each of the two arrays in listing 8.2 between square brackets.

Listing 8.2. Using existing objects in an array (http://jsbin.com/gizulu/edit?js,console)

You’ve created an array and assigned it to a variable, so now you can pass that variable to functions, like console.log. At some point you’ll want to access the elements that make up the array, to peel away the skin to get at the juicy goodness inside. Well, those square brackets do double duty; they enclose the list when you define the array, and you use them to access individual elements.
As shown in figure 8.3, you specify each element with an index, a whole number marking where in the list the element occurs. The first element in an array has an index of 0, the second an index of 1, and so on. You can think of the index as an offset from the start of the array; the first element is zero away from the start, the second is one away from the start, and so on.
To retrieve the value of an element at a given index, put the index inside square brackets after the name of a variable to which the array has been assigned, as shown in figure 8.4.
Here, you create an array and assign it to a variable:
To get the value of the third item in the array, 8, place the index, 2 (because you start with 0), in square brackets after the name of the variable:
You can assign scores[2] to another variable, set it as a property on an object, use it in an expression, or pass it as an argument to a function. Listing 8.3 creates strings using the values of elements in the scores array and displays them on the console to give the following:
It also makes use of the array’s length property that simply gives the number of elements in the array.
Listing 8.3. Accessing array elements (http://jsbin.com/qemufe/edit?js,console)

Now, say you have a days array, holding the names of the weekdays, and you want to get the name of a particular day in the week, maybe the fourth day.
There’s a mismatch between the index in JavaScript and the words used to describe a particular element. The first day of the week has index 0. The fourth day of the week has index 3. You might want to access a different day at different times, so you could use a variable, dayInWeek, to hold the day in the week you want.
But using dayInWeek as the index for the array will give you the wrong day. An index of 4 will give you the fifth day in the week.
The next listing shows code for this scenario. It displays two days on the console: the wrong one (that is, not the fourth day of the week) and then the right one:
Listing 8.4. Using a variable as an index (http://jsbin.com/veyexa/edit?js,console)

The first call to console.log displays the wrong day because the dayInWeek variable doesn’t take into account that arrays are zero-based; they start with an index of 0, not 1. The second call to console.log fixes the problem by subtracting one from dayInWeek; the fourth day of the week has an index of 3.
Okay. It’s time to hold onto your hat. In listing 8.5 you’ll define a function and add it to the mix. The local pencil museum records the number of visitors through its doors each day. The owners ask you to create a program that, when given a week’s worth of visitor numbers as an array, will display how many visitors there were on a given day:
You decide to write a function, getVisitorReport, to generate the report and return it. You then would have the option of displaying the report on the console, on a web page, or in an email. In the next listing you generate a report for a Tuesday and display it on the console.
Listing 8.5. Passing an array to a function (http://jsbin.com/bewebi/edit?js,console

You create an array of visitor numbers, assign it to the visitors variable, and pass it to the getVisitorReport function as an argument. Within the function, the array is assigned to the visitorArray variable and used to generate the report. The report is returned from the function, assigned to the report variable, and displayed on the console. The += operator in the function adds the value on its right to the variable on its left. Because a string has been assigned to the visitorReport variable, += concatenates the value on its right to the variable on its left.
So, you can create an array and access its elements. But, once you have data in an array, there’s a whole host of ways you can manipulate it. Let’s get started with a few of the most common ways to work with arrays.
Arrays are a type of object provided by the JavaScript language to help you manage lists. JavaScript also provides you with a number of functions you can use to work with arrays. When we assign functions to properties of an object, we call the functions methods of the object; arrays are a type of object, so their functions are also called methods.
In this section you look at just a few of the many methods available when working with arrays: push and pop and splice let you add and remove elements, slice lets you grab consecutive elements, join lets you concatenate the array elements to form a string, and forEach allows you to pass each element as an argument to a specified function. These methods are summarized in table 8.1. Further array methods and examples can be found on the book’s website at www.room51.co.uk/js/array-methods.html.
Table 8.1. Array methods
Method |
What’s it for? |
Example |
---|---|---|
push | Appending an element to the end of an array. | items.push("Put me last"); |
pop | Removing an item from the end of an array. | wasLast = items.pop(); |
join | Concatenating all of the elements in the array, inserting an optional string between each pair of elements. | allItems = items.join(","); |
slice | Creating an array from a range of elements in an existing array. Passing in the indexes at which to start and stop the range. | section = items.slice(2, 5); |
splice | Changing an array by adding and/or removing consecutive elements. Passing in the index at which to start removing elements, the number of elements to remove, and any elements to add. | out = items.splice(1,2,"new"); |
forEach | Passing each element in turn to a specified function. | items.forEach(function (item){ console.log(item); } |
Let’s begin with push, pop, and join.
In listing 8.6, you create an empty array and assign it to the items variable. The push method is used to append three elements to the array. Once you’ve added the three elements, you log the whole array to the console:
You then use the pop method to remove the last item and display it. Finally, you log the whole array to the console again, this time with the elements joined to make a single string.
Listing 8.6. Manipulating arrays with push, pop, and join (http://jsbin.com/faqabu/edit?js,console)

JavaScript makes the push, pop, and join functions available as properties on every array. Because they’re properties of the array, you can use dot notation to call the functions, items.push(itemToAdd), just as you can to access any object property.
To demonstrate the two array methods, slice and splice, you continue with your array of holiday destinations. Play along on the JS Bin console. Commands can span multiple lines on the console; press Shift-Enter to move to a new line without executing a statement. If you press Enter by mistake and execute an unfinished statement, you may be able to retrieve your previous entry by pressing the up arrow on your keyboard. The statements that you type are shown starting with >. The console automatically shows the return value of each function called. I show those values in bold.
The slice method returns a new array made up of part of the original array. It doesn’t change the original array. The arguments are the index of the first element you want and the index of the first subsequent element you don’t want. Remember, the first element has index 0.
items.slice(2, 3) says you want the items from index 2 onward but not the items from index 3 onward. In other words, you just want the item with index 2.
Omit the second argument if you want all elements after the one specified by the first argument. Omit both arguments if you want the whole array.
The splice method does change the original array. It lets you remove items from an array and, optionally, insert new items. To remove items, specify the index of the first element to remove and the number of elements to remove. The method returns the removed elements as an array.
To insert new elements into the array, add them as arguments after the start index and the number of items to remove. In this example, no items are removed:
In this example, one item is removed:
You’ll use both slice and splice when working with player and place items in The Crypt.
If you have a list of items that you want to display on the console, you could manually call a function for each one:
Unfortunately, it’s common not to know in advance how many items will be in the list, so you can’t hard-code the right number of showInfo calls ahead of time. Also, as the number of elements increases, you don’t want to be manually calling a function for each one.
What you need is a way to make JavaScript call a given function for every element in the list, however many there are. That’s exactly what the forEach method does. To call showInfo for each element in the items array, replace the individual calls with
The forEach method iterates over the array, passing each element in turn as an argument to the function specified in parentheses, as shown in figure 8.5.
Listing 8.7 shows forEach in action, displaying the elements of an items array on the console:
Listing 8.7. Iterating over an array with forEach (http://jsbin.com/sokosi/edit?js,console)

In listing 8.7, your function to display each item was assigned to the showInfo variable. You then passed the showInfo variable to forEach as an argument.
If you’re going to use a function only once, as the argument for forEach, you can create the function and pass it to forEach inline, without the need for an extra variable. The code in listing 8.8 passes the function definition directly to forEach. You also add extra information to set the scene and improve the output:
Listing 8.8. Calling forEach with an inline function (http://jsbin.com/yapecu/edit?js,console)

The forEach method actually passes three arguments to the specified function: the element, the index of the current element, and the whole array. You can capture the extra arguments by including extra parameters in the definition of the function you pass to forEach.
Listing 8.9 shows all three arguments in action. It uses forEach to pass each player in the players array to the showArguments function, producing the following output:
Listing 8.9. Using the arguments passed by forEach (http://jsbin.com/suvegi/edit?js,console)

The forEach method does the job of calling a function for you. In listing 8.9, it calls the showArguments function. It calls the function for each element in the players array. It always passes the three arguments to the function it calls, although you don’t have to use all three.
You can call array methods like forEach directly on arrays without the need for variables. Listing 8.10 rewrites listing 8.9 without assigning the array or the function to variables.
Listing 8.10. Using the arguments passed by forEach—compact (http://jsbin.com/pagahe/edit?js,console)
If you’re using the array and function only once, the compact syntax in listing 8.10 can be appropriate. But the longer form in listing 8.9 is more readable, so if the meaning of the code isn’t obvious in context, it might be better to opt for the longer version. Being able to write something like
can help you and other programmers make better sense of your code.
To further demonstrate using the index argument, you’re off to the shops in listing 8.11. (If you have your adventure head on, then maybe you’re buying equipment for your travels.) You buy four types of items but different amounts of each. The program calculates the total cost and displays it, like this:
It uses two arrays, one for the numbers of each item bought and one for their costs.
Listing 8.11. Finding the total shopping bill (http://jsbin.com/zizixu/edit?js,console)

Listing 8.11 uses the index to match the current item cost with the correct number of items. For this to work, the arrays have to be in the same order. I hope you noticed that i isn’t a very descriptive variable name! It is so common to need index variables that most programmers are happy to use short names—i, j, and k—for them. They’re quicker to type and it’s such a well-established convention that most people reading your code will expect them to be used as a counter or index. If you’d rather call the variable index or itemIndex or something similar, that’s fine.
As one last example, let’s return to your quiz questions. A multiple-choice question has a list of possible answers that need to be displayed to whomever is taking the quiz. Sounds like a good fit for an array and forEach; see listing 8.12. You could even have an array of question-and-answer objects. For now, stick with a single question, displayed like this:
Listing 8.12. Displaying a multiple choice question (http://jsbin.com/lobahu/edit?js,console)

You’ll look at actually answering questions when you investigate user interaction in part 2.
You’ll now apply your knowledge of JavaScript arrays to The Crypt. Figure 8.6 shows where the focus of this section, displaying a list of player items by using arrays, fits into the overall structure of our ongoing game example.
In part 1 of Get Programming with JavaScript, we’ve covered some core concepts to help you model and use players in The Crypt. You have variables to store and retrieve player information, objects to collect player properties together, arrays so you can list the items a player collects, array methods to add and remove items in the collection, and functions to display information about each player.
Listing 8.13 brings all of these concepts together: creating a player, displaying information about them, picking up a new item, and displaying the updated info. You format the output using the spacer namespace developed in chapter 7. The elements that make up the output are highlighted in figure 8.7.
To save space, spacer isn’t shown in the listing (it hasn’t changed) but it is on JS Bin. The code in this listing builds on the player display code from chapter 7, adding the ability to list a player’s items.
Listing 8.13. Displaying player items (http://jsbin.com/mecude/edit?js,console)


It starts with only one element, but you add another by using the push array method:
getPlayerItems uses forEach to pass each item in the items array to a function. The function appends the item to a string using +=, building a list of all of the player’s items:
The showPlayerInfo function calls getPlayerInfo to retrieve the player information string and then displays the information on the console.
You’re starting to build up quite a collection of functions to help with the display of players; you should really organize them. You could collect them into a namespace or, seeing as they all relate to players, include them as part of each Player object. JavaScript provides a way to streamline the creation of many similar objects, incorporating the methods that work with them: constructor functions. That’s what you investigate in chapter 9, where you also build the places the players will explore in The Crypt.
- Create an array with a comma-separated list of values between square brackets:
- Assign the array to a variable and then access its elements by adding an index in square brackets to the variable name. The following code displays "Dax":
- Remember to use a zero-based index for array elements. items[1] refers to the second element in the items array. You can think of the index as an offset from the start of the array: the first element is zero away from the start, the second is one away from the start, and so on.
- Use array methods, functions provided by JavaScript, to add, remove, join, and iterate over array elements. The methods covered in this chapter are push, pop, join, slice, splice, and forEach.