In this video, you printed your day-hike packing list one item per line with a for...of loop.
Key Points
- A
for...ofloop visits each item of an array, one pass per item, in the order the items sit in the list. - On each pass, the loop puts the current item into the name you write after
const, hereitem, and then runs the body between the curly braces. - Each pass gets its own fresh
item, soconstworks even though the value is different every time. - After the last item, the loop ends and the program carries on.
- An item you
.push()onto the list gets its own pass at the end, without any change to the loop. - An empty array has no first item, so the loop makes zero passes and its body never runs. That’s not an error.
Final Code
packing.js
const packingList = ["water bottle", "rain jacket", "map"];
packingList.push("snacks");
for (const item of packingList) {
console.log(item);
}
$ node packing.js
water bottle
rain jacket
map
snacks
And with an empty list:
bag.js
const emptyBag = [];
for (const item of emptyBag) {
console.log(item);
}
console.log("Bag checked.");
Bag checked.