Arrays
Learn about arrays with examples.
So far, we’ve met primitive data types, such as strings, numbers and Booleans. But what if we want to store a whole collection of values in a single variable? For example, we might have a list of prices that we want store in the same place. Composite data types can be used to collect primitive values in a structured way.
Programming languages use a variety of different data structures to store values, but one of the most common is an array.
What is an array?
An array is an ordered list of values. For example, consider the following shopping list:
- Apple
- Banana
- Cupcake
This could be represented as the following array:
['Apple', 'Banana', 'Cupcake']
console.log(['Apple', 'Banana', 'Cupcake']);
Each value in the array has a numerical index that shows its position in the
array. In the example above, 'Apple'
has an index of (remember that
computers start counting at zero!), 'Banana'
has an index of , and
'Cupcake'
has an index of .
Arrays can contain any type of value, such as numbers:
[2, 3, 5, 7, 11]
Or strings:
['Dog', 'Cat', 'Rabbit']
Or Booleans:
[ false, true, true, false, true ]
In most languages, including JavaScript, we’re not restricted to using the same types of items inside arrays either. This array contains a variety different data types: