Skip to content

Exercise 8 of 10 · Arrays

Packing List

What you will make

A travel checklist with a banner, one tick-box line for every item sitting inside the square brackets, and a footer that counts the items without being told how many there are.

The one new idea: an array holds several values in order, and for...of walks through them

Most of the data a program handles arrives in bunches: the songs in a playlist, the rows of an order, the messages in an inbox. An array is how JavaScript keeps a bunch of values under one name, and a for...of loop is the plainest way to do the same thing to every one of them without knowing in advance how many there will be.

Go straight to the code ↓

An array is many values under one name

Every name you have made so far has held one thing: one greeting, one score. A packing list is several things, kept in the order you wrote them, all answering to the same name.

JavaScript writes that with square brackets and a comma between the values:

JavaScript
const items = ["Passport", "Charger"];

One const called items, holding two pieces of text: Passport first, Charger second, and they stay that way for as long as the program runs. Adding a third means typing a comma and another value inside the same brackets. The brackets make it an array; the commas keep the values apart.

A loop whose variable is not a number

for (let i = 5; i >= 1; i--) counts. You wrote the start, the test and the step, and everything it handed you was a number.

for (const item of items) counts nothing. It walks along the array and hands you the value sitting there — the text "Passport", then the text "Charger". You never say how many passes to take, because the array already knows how long it is. And the name between const and of holds a piece of text, which is new: until now, the variable a loop handed you was always a number.

const is right there even though the value differs on every pass. The counting loop needed let because one name was changed over and over; here each pass gets a fresh name with the next value already in it, so nothing is ever assigned twice.

JavaScript
for (let n = 1; n <= 3; n++) {
  console.log(n);
}

for (const word of ["yes", "no", "maybe"]) {
  console.log(word);
}
Output
1
2
3
yes
no
maybe

Two loops that look alike on the page and behave nothing alike. The name after const is yours to choose — item, word, chore — and JavaScript puts the next value into it each pass.

.length says how many

items.length is the number of values in the array. It is a property, not something you call: it gives 2 here, while items.length() stops the program with TypeError: items.length is not a function. It is read fresh every time, so an array that grows reports a bigger number on its own.

A worked example

A chore board rather than a suitcase, so the checklist stays yours to finish:

JavaScript
const chores = ["Sweep", "Wash up", "Bins"];

for (const chore of chores) {
  console.log(`Today: ${chore}`);
}

console.log(`${chores.length} jobs on the board`);
Output
Today: Sweep
Today: Wash up
Today: Bins
3 jobs on the board

Three values, three lines, then one line that counted them. Put a fourth chore inside the brackets and you get a fourth line and a 4 at the bottom.

Your turn

The editor holds a checklist with two items on it. Press Run before changing anything.

The loop is already doing its half: two items, two passes, two lines. But both lines read [ ] item, because the line inside the braces prints the word item in double quotes, and double quotes mean ordinary characters.

Two things to do:

  1. Rewrite that line as a template literal, so it prints the value instead. Keep the [ ] box and the space after it — those square brackets sit inside the quotes, so they make no array.
  2. Add "Socks" and "Towel" to the array, in that order, each with a comma in front of it.

The footer needs no attention: it already asks the array how many values it holds, so it says 4 by itself once the new items are in place.

If something goes wrong

If every line reads [ ] ${item} back at you, braces and all, the line is still in double quotes. Nothing has broken; the quotes need to be backticks.

If nothing appears at all — no banner, no lines — JavaScript refused to start, because the whole file has to make sense before any of it runs. Two slips do that here. A missing comma between two items inside the square brackets gives SyntaxError: Unexpected string. A line that opens with a backtick but closes with a double quote, or the other way round, leaves the text unfinished, so the quotes on both sides of the box must match. An empty panel is nearly always punctuation rather than a wrong idea.

And if every line reads [ ] Passport,Charger,Socks,Towel, the braces hold items where they should hold item. The array turns itself into text without complaint; the singular name is the one the for line hands you.

Change the list, run it again, and read your own checklist.

Write your code

Runs in your browser. Press Run (or Ctrl/Cmd+Enter) and the output is checked for you.

Ctrl/Cmd+Enter to run

Press Esc then Tab to move keyboard focus out of the code editor.

Ready
Output will appear here after you run your code.

The runtime is starting in the background. You can type now — it will be ready before you are.

The answer appears here once you have run your code at least once.

Things that often go wrong here

Leaving the line in double quotes
Double quotes make the dollar sign and the braces ordinary characters, so every line prints those characters back at you instead of the item, and all the lines still look identical. No error appears, because a piece of text with braces in it is a perfectly reasonable thing to want. Only backtick quotes bring the braces to life.
Asking for the count with round brackets after length
Putting round brackets on the end stops the program with TypeError: items.length is not a function. The length of an array is something it already knows, not a question you call. Take the brackets off and the number appears.
Forgetting the comma between two items
Two pieces of text side by side inside the square brackets with nothing between them stop the program before a single line runs, with SyntaxError: Unexpected string. The output panel stays completely empty, banners and all, and that emptiness is the tell: nothing ran, rather than something running wrongly.
Putting the plural name inside the braces
The plural name is the whole array, and an array dropped into a piece of text turns itself into all its values joined by commas. Every line then reads the same long row of names. The singular name is the one the for line hands you, one value per pass.
Typing the footer number in by hand
The footer asks the array how many values it holds, so it is already right the moment an item is added or taken away. A typed number is correct once and wrong from the next edit onwards.

Want a blank editor instead? Open the JavaScript playground.