Arrays: Lists of Values
Create arrays, read and change items by index, add and remove items with push, pop and splice, and search with includes and indexOf.
Welcome back!
Step 1 of 12Learn
One variable, many values
A music app needs your playlist. Storing it as song1, song2, song3 and so on would be hopeless: how would you add a song, or loop over 500 of them? An array is an ordered list of values held in one variable:
const playlist = ["Intro", "Skyline", "Night Drive", "Outro"];Each item has an index, its position, and indexes start at 0:
playlist[0] // "Intro"
playlist[2] // "Night Drive"
playlist.length // 4
playlist[playlist.length - 1] // "Outro" (the last item)
playlist[10] // undefined (no item there)Zero-based indexing confuses everyone at first. The first item is at 0, so the last item is at length - 1, not length. Reading playlist[playlist.length] gives undefined, a very common off-by-one bug. Newer code can also use playlist.at(-1) to get the last item.
Arrays can hold any type, including a mix: [42, "text", true, null]. They can even hold other arrays, which is how you represent grids like a game board: board[row][col].
You can change an item by assigning to its index: playlist[1] = "Sunrise";. This works even when the array is declared with const: const prevents reassigning the variable to a new array, not changing the array's contents.
Step 2 of 12Practice · Diagram
playlist: positions start at 0
Which item is playlist[playlist.length - 1]?
Tap the shape that answers the question, then press Check.
- [0] "Intro"
playlist[0]: the first item.
- [1] "Skyline"
- [2] "Night Drive"
- [3] "Outro"
Index 3 although it is the 4th item, because length is 4.
Step 3 of 12Practice · Fill in the blanks
Fill in the blanks
Given const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];, the value of days[3] is , and days.length is .
Step 4 of 12Learn
Adding, removing and searching
Arrays come with built-in methods. The four for the ends of the list:
| Method | What it does | Returns |
|---|---|---|
push(x) | adds x to the end | new length |
pop() | removes the last item | the removed item |
unshift(x) | adds x to the start | new length |
shift() | removes the first item | the removed item |
const cart = ["milk", "bread"];
cart.push("eggs"); // ["milk", "bread", "eggs"]
cart.shift(); // removes "milk" → ["bread", "eggs"]To work in the middle, splice(start, deleteCount, ...items) removes and/or inserts: cart.splice(1, 1) removes one item at index 1.
Searching:
includes(x)→ true or false:cart.includes("eggs")indexOf(x)→ the first index of x, or -1 if it isn't therejoin(sep)→ combines items into a string:["a", "b"].join("-")gives "a-b"
Copying without changing: slice(start, end) returns a new array from start up to, but not including, end. [10, 20, 30, 40].slice(1, 3) gives [20, 30].
Watch the difference between methods that change the original array (push, pop, shift, unshift, splice, sort, reverse) and those that return a new one (slice, concat, map, filter). Mixing them up leads to data changing when you didn't expect it.
Step 5 of 12Compare
Working at the two ends of an array
| Aspect | At the end | At the start |
|---|---|---|
| Add an item | push(x) | unshift(x) |
| Remove an item | pop() | shift() |
| Add returns | the new length | the new length |
| Remove returns | the removed item | the removed item |
| Speed on big arrays | Fast | Slower: every item shifts position |
Step 6 of 12Practice · Match the pairs
Start with const a = [1, 2, 3]; each time. Match each call to the array it leaves behind.
Tap an answer, then tap the place where it belongs (or drag it there).
- a.push(4)
- a.pop()
- a.shift()
- a.unshift(0)
- a.slice(1)
Step 7 of 12Note
Step 8 of 12Practice · Code challenge
Write a function lastItem(arr) that returns the last item of an array, or undefined if the array is empty.
lastItem([1, 2, 3])lastItem(["a"])lastItem([5, 9])
Step 9 of 12Note
Step 10 of 12Practice · What would you do?
What would you do?
You loop over an array of 5 items with for (let i = 0; i <= arr.length; i++) and print arr[i]. The output shows the 5 items and then undefined. What is the fix?
Step 11 of 12Tap to reveal
Arrays in real applications
A shopping cart
Each item a customer adds is pushed onto an array. The cart badge shows cart.length, removing an item uses splice or filter, and the checkout total comes from adding up the prices. Almost every online store is built on exactly these operations.
A chat window
Messages arrive in order and are pushed to the end of an array. The screen shows the most recent ones, often with slice(-50) to take only the last fifty, so the page stays fast even after thousands of messages.
A game board
A tic-tac-toe or chess board is an array of rows, each row an array of squares: board[row][col]. Checking for a winner means looping over rows, columns and diagonals.
Search results and feeds
When a site loads posts, products or search results, the server usually sends an array of objects. The page loops over it to build the list you scroll through, which is why the next two lessons on array methods and objects matter so much.
Step 12 of 12Practice · Choose one
What does ["red", "green", "blue"].indexOf("purple") return?
Lesson complete!