Table of Contents

11.1 What Is an Array?

An array is a data structure that can encompass multiple individual data values, just like a building is a physical structure encompassing multiple floors. Unlike a primitive datatype, an array can include more than one data value. Here is a simple example showing two separate strings, followed by an array that contains two strings:

"oranges"              // A single primitive string value
"apples"               // Another primitive string value
["oranges", "apples"]  // A single array containing two strings

An array is a general-purpose container. It can contain any number of items, including items of different types. An array can even contain other arrays. Here is a simple example showing an array that contains both strings and numbers. It might represent your shopping list and how many of each item you intend to buy:

shoppingList = ["oranges", 6, "apples", 4, "bananas", 3];

Here's another analogy to make the concept of an array a little more tangible. Consider a chest of drawers. An individual drawer contains some content (socks, shirts, etc.). But the chest itself doesn't contain the content; it contains the drawers. The drawers hold the content. The chest organizes the drawers into a single unit.

When we work with an array (the chest of drawers), we usually are interested in the values within the array (the contents of the drawers). But we can also manipulate the containing structure itself. For example, we can change an array's size (add or subtract drawers) or reorder its values (swap the contents of its drawers).

Though we speak of an array as containing many values, it's important to recognize that the array itself is a single datum, in the same way that a string containing multiple characters is still a single string, and a number containing several digits is still a single number. As a single datum, an array can be assigned to a variable or used as part of a complex expression:

product = ["ladies downhill skis", 475];  // Store an array in a variable
display(product);                         // Pass that array to a function

Table of Contents