{module 5}
Lists and loops
Your first JavaScript20 min read
What you will be able to do
- Keep a list of things, each with several details, as an array of objects.
- Go through every item of an array with a
for...ofloop. - Build a list on the page from data, with
createElementandappend.
Why it matters
Roti Stop sells takeaway food in Port of Spain, Trinidad and Tobago. The menu on its page changes most days: one dish sells out, another comes back. Kavita, the owner, asked her nephew Marcus to update the page each morning. He edited the HTML by hand, item by item. One Friday he copied a line to add a dish and forgot to change the price, so the page showed chicken roti for $1.50. Customers arrived expecting that price.
The menu is really a short list of data: a name, a price, and whether it is sold out. When the data is kept in one place and the page is built from it, changing the menu means changing a word in the data, and every line of the page follows the same pattern.
The idea
An array: a list of values
An array is a list of values in one variable, written between square brackets with commas between the values:
const dishes = [The values in an array are its items. Each has a position called its index, counted from 0. dishes[0] is the first item and dishes[1] the second. dishes.length is how many items there are.
An object: one thing with named details
In lesson 3 you met an object in the formatter's settings. An object groups several values under names, between curly brackets. Each name and its value is a property:
{ name: "Chicken roti", priceCents: 900, soldOut: false },This object is one dish. You read a property with a dot: if dish is this object, dish.name is "Chicken roti" and dish.priceCents is 900. You have used the dot in the same way since lesson 1, with field.value.
An array of objects
Put the two together and you have the menu: an array whose items are objects, one per dish, each with the same property names.
const dishes = [
{ name: "Doubles", priceCents: 150, soldOut: false },
{ name: "Chicken roti", priceCents: 900, soldOut: false },
{ name: "Aloo pie", priceCents: 200, soldOut: true },
{ name: "Bake and saltfish", priceCents: 650, soldOut: false },
];Every object ends with a comma, including the last one. JavaScript allows the comma after the last item, and it means a new dish can be added without touching the line before it.
A loop: the same steps for each item
A loop runs the same block of code several times. The for...of loop runs it once for each item of an array:
for (const dish of dishes) {Read it as: for each dish of the dishes, run the block. The first time, dish is the first object. The second time, it is the second. When there are no items left, the loop ends and the script goes on to the next line after the closing bracket. dish can be a const, because each turn of the loop makes a new variable.
Making elements
document.createElement("li") makes a new li element. It exists only in memory, and the page does not show it yet. append puts it inside another element, after anything already there:
menuList.append(item);So each turn of the loop makes one list item, gives it text with textContent, and appends it to the empty list in the HTML.
A boolean in an if
In lesson 4 every if had a comparison. An if accepts any true or false value, so a boolean property can go in directly. if (dish.soldOut) runs its block when soldOut is true.
Worked example
Create index.html, styles.css and menu.js in a new folder and save them. The list in the HTML is empty: the script fills it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Today's menu, Roti Stop</title>
<link rel="stylesheet" href="styles.css" />
<script src="menu.js" defer></script>
</head>
<body>
<main>
<h1>Roti Stop</h1>
<h2>Today's menu</h2>
<ul id="menu"></ul>
<p id="summary"></p>
</main>
</body>
</html>body {
max-width: 40rem;
margin: 0 auto;
padding: 1rem;
font-family: Arial, sans-serif;
line-height: 1.5;
}
#summary {
font-weight: bold;
}// Today's dishes. Prices are in cents.
const dishes = [
{ name: "Doubles", priceCents: 150, soldOut: false },
{ name: "Chicken roti", priceCents: 900, soldOut: false },
{ name: "Aloo pie", priceCents: 200, soldOut: true },
{ name: "Bake and saltfish", priceCents: 650, soldOut: false },
];
const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const menuList = document.querySelector("#menu");
const summary = document.querySelector("#summary");
let available = 0;
for (const dish of dishes) {
const item = document.createElement("li");
if (dish.soldOut) {
item.textContent = `${dish.name}: sold out`;
} else {
item.textContent = `${dish.name}: ${dollars.format(dish.priceCents / 100)}`;
available = available + 1;
}
menuList.append(item);
}
summary.textContent = `${available} of ${dishes.length} dishes available today`;
console.log(dishes[0].name, dishes.length);Open the page. It shows:
Roti Stop
Today's menu
Doubles: $1.50
Chicken roti: $9.00
Aloo pie: sold out
Bake and saltfish: $6.50
3 of 4 dishes available todayThe Console shows the name of the first dish and the number of dishes:
Doubles 4Read menu.js from the top. Lines 2 to 7 are the data, the only part Marcus changes each morning. Lines 9 to 11 make the formatter and find the empty list and the summary.
Line 13 makes a counter, available, that starts at 0. It uses let because it changes.
Lines 14 to 23 are the loop. It runs four times. Each time it makes a list item, writes either "sold out" or the price into it, and appends it to the list. Each dish that is not sold out adds 1 to the counter.
Line 25 runs once, after the loop has finished, so the counter is complete. The HTML file still has an empty list. Everything you see in it came from the data.
Now make Marcus's morning change. On line 5, change true to false, save and reload. Aloo pie shows its price, and the summary says 4 of 4.
Common mistakes
Replacing instead of adding
In this version, each turn of the loop writes into the list itself instead of making an item:
for (const dish of dishes) {
if (dish.soldOut) {
menuList.textContent = `${dish.name}: sold out`;
} else {
menuList.textContent = `${dish.name}: ${dollars.format(dish.priceCents / 100)}`;
available = available + 1;
}
}Bake and saltfish: $6.50There is no error, and only the last dish is shown. Setting textContent replaces everything inside an element, so each turn removed the dish before it. To add, make a new element in each turn and append it. If you make the items and forget the append, the list stays empty, also with no error.
A missing comma between objects
Here line 4, the chicken roti, has no comma at the end:
{ name: "Chicken roti", priceCents: 900, soldOut: false }Roti Stop
Today's menu
page error: Uncaught SyntaxError: Unexpected token '{'The list is empty, and the Console names a SyntaxError. Syntax is the set of rules for how code is written. A syntax error means the browser could not read the file at all, so no line of it ran. "Unexpected token '{'" means the browser found a { where it expected something else. It expected a comma or a ] after the chicken roti, and found the next dish. In your browser the line number beside the message is 5, the line after the real mistake. With a syntax error, look at the line named and the line before it.
A property name that does not exist
item.textContent = `${dish.name}: ${dollars.format(dish.price / 100)}`;Doubles: $NaN
Chicken roti: $NaN
Aloo pie: sold out
Bake and saltfish: $NaNThe objects have priceCents, not price. Asking an object for a property it does not have gives undefined, with no error, and undefined / 100 is NaN, as in lesson 2. The names used in the loop must match the names in the data exactly.
Think it through
Aroha keeps a small order as an array of objects, each with a name, a priceCents and a quantity. She wants the page to show the total of the order.
Understand. In: an array of items. Out: one amount in dollars. Each item adds its price times its quantity.
Break down. Start a total at 0. For each item, work out its cost and add it. Show the total after the loop.
Plan. let totalCents = 0; before the loop. Inside a for...of loop, totalCents = totalCents + item.priceCents * item.quantity;. After the loop, format the total and set the text of a paragraph.
Build. She writes the loop with console.log(item.name, totalCents) inside it first, so she can watch the total grow in the Console, one line per item.
Test. Two items, 2 at $1.50 and 1 at $9.00, should give $12.00. The Console shows 300 after the first item and 1200 after the second, and the page says $12.00. The odd case is an empty array: the loop never runs, and the page shows $0.00, which is right.
Reflect. Printing inside the loop showed each step, not only the end. If the total had been wrong, she would have seen which item made it wrong.
At work
A handover note is what you leave for the person who will look after a project when you stop. Its most useful line is the first thing they should do. A new person facing a whole folder of files does not know where to start.
Marcus is leaving for university and hands the page to his cousin. His handover note in the README says:
If you are taking over this page
Start with the first seven lines of
menu.js. They are the menu, and they are the only part you will change on most days.
- To mark a dish as sold out, change
falsetotrueon its line.- To add a dish, copy a whole line, from
{to the comma, and change the name and the price. Prices are in cents.After any change, open
index.htmlin a browser with the Console open. If the list is empty, look for a missing comma on the line before the one the Console names.
The note puts the most common job first, gives each step as an action, and warns about the mistake Marcus made most often.
Your tasks
Task 1: Build the menu
Create the three files and open the page. Then add a fifth dish of your own and mark Doubles as sold out.
You are done when the page lists five dishes, Doubles says "sold out", and the summary says "3 of 5 dishes available today".
Task 2: Remove a comma
Delete the comma at the end of one dish, reload, and read the Console. Click the file name beside the message. Put the comma back.
You are done when you have written down the message and the line it names, and can say which line had the real mistake.
Task 3: The cheapest dish
Under the summary, show a line such as "Cheapest today: Doubles, $1.50". Only dishes that are not sold out count. Use the loop that is already there, and decide what the line says when every dish is sold out.
You are done when the line names the cheapest available dish, changes when you mark that dish as sold out, and shows your chosen words when all are sold out.
Recap
- An array keeps a list of items in order.
dishes[0]is the first, anddishes.lengthis how many there are. - An object groups named properties. Read one with a dot, as in
dish.priceCents. for (const dish of dishes)runs a block once for each item.createElementmakes an element in memory, andappendputs it on the page.textContenton the list itself replaces everything.- A syntax error stops the whole file. Look at the line named and the one before it.
Go deeper
- MDN: Arrays explains arrays, indexes and
lengthfor beginners. - MDN: JavaScript object basics shows objects, properties and the dot.
- MDN: for...of is the reference page for the loop.
- MDN: Document.createElement() shows how to make an element and add it to a page.