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 first, two strings, and then 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 and even items of different types. An array can even contain
other arrays. Here is a simple example showing an array containing
both strings and numbers. It might represent your shopping list and
how many of each item you intend to buy:
["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 are usually
interested in the values within the array (the contents of the
drawers). The values contained in an array are the information we
want to manage. But we may also manipulate the containing structure
itself. We may, for example, 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 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 may 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