Arrays
An array is an ordered list of values stored under one name. Instead of juggling separate variables like city1, city2, and city3, you keep one array and let position do the organizing.
Creating an array
Square brackets create an array literal, with items separated by commas. length tells you how many items are in it:
Indexing
Each item has a position called its index, and indexes start at 0, not 1. So in a three-item array, the first item is cities[0] and the last is cities[2]:
cities.length - 1 is a useful trick — it always points at the last item, no matter how long the array is.
Changing an item
Assigning to an index replaces the value that's there:
const doesn't lock its contents — it only stops cities from being reassigned to point at a completely different array. Changing, adding, or removing items is still allowed.Adding and removing items
push adds an item to the end of an array; pop removes the last item and hands it back to you. They're the two you'll reach for most:
There's also unshift and shift, which do the same job at the front of the array instead of the end. They come up far less often, mostly because adding or removing from the front means every other item has to shift position.
Common mistakes
- Reading an index that doesn't exist —
cities[10]on a 3-item array — doesn't throw an error. It quietly returnsundefined, which tends to surface as a bug much later. - Off-by-one errors: the last valid index is
length - 1, notlength. - Assuming two arrays with the same items are "equal" —
[1, 2] === [1, 2]is actuallyfalse, because===compares arrays by reference, not by contents.