So far in this course, you’ve built lists with .push(), counted their items with .length, and visited every item in order with a for...of loop. A loop is the right tool when you want all the items. But often you only care about one: the first song on a playlist, the last thing you packed, or the one entry with a typo in it.
To reach a single item directly, you use its position in the list. You’ve already done this with strings, and arrays work almost the same way. In this lesson, you’ll read items by position, reach the last item even as the list grows, and replace an item without touching the rest.
Start From String Positions
In an earlier course, you read single characters out of a string by their position. Take a moment to warm that skill back up. With const word = "hike";, decide what each of these expressions gives before you look.
word[0]word[3]word[word.length - 1]word[4]
Then open the Node.js REPL by typing node in the terminal, and enter the lines one at a time to check your answers.
> const word = "hike";
undefined
> word[0]
'h'
> word[3]
'e'
> word[word.length - 1]
'e'
> word[4]
undefined
The first character sits at position 0, so the last one sits at length - 1. Asking for a position past the end isn’t an error. JavaScript hands you undefined, its way of saying “there’s nothing here.” Keep these three rules in mind, because arrays follow every one of them, with items in place of characters.
Read an Item by Its Index
Picture a playlist for a long train ride. Type .exit to leave the REPL, then create a file named playlist.js in your course folder. When a list gets long, you can write its array literal across several lines, with one item per line, which keeps it readable.
playlist.js
const playlist = [
"Rainy Day Waltz",
"Sunny Side Up",
"Mountain Echo",
"Last Train Home"
];
console.log(playlist[0]);
console.log(playlist[2]);
The number in square brackets is the item’s index, its position in the array. Like string positions, array indices are zero-based, which means counting starts at 0. Before you run the script, predict which two songs it prints.
$ node playlist.js
Rainy Day Waltz
Mountain Echo
The first song is at index 0, and playlist[2] is the third song. If you predicted “Sunny Side Up” for index 2, you counted the way people number songs, starting at one. That’s a very human slip, and subtracting one from the song’s number fixes it.