From Zero to Senior · The LabالعربيةGitHub

Chapter 9

Loops and Arrays

6 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • store many values in one variable with arrays
  • read, add and find items in an array
  • repeat work with for, for…of and while loops
  • stop a loop early or skip a step with break and continue
  • serve a whole queue of visitors with your ticket kiosk

Examples

9.1 Arrays: lists of values

An array is an ordered list of values stored in one variable. You write it with square brackets, separating the items with commas:

arrays.js⤓ File
const fruits = ["apple", "banana", "mango"];

console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);

fruits.push("orange");
console.log(fruits);

console.log(fruits.includes("banana"));
console.log(fruits.indexOf("mango"));
Recorded output$ node arrays.js
[ 'apple', 'banana', 'mango' ]
3
apple
mango
[ 'apple', 'banana', 'mango', 'orange' ]
true
2

9.2 The for loop

A loop runs the same block of code several times. The classic for loop counts:

for.js⤓ File
for (let i = 1; i <= 5; i++) {
  console.log(`Step ${i}`);
}

// Counting down
for (let n = 3; n > 0; n--) {
  console.log(n);
}
console.log("Go!");
Recorded output$ node for.js
Step 1
Step 2
Step 3
Step 4
Step 5
3
2
1
Go!

9.3 for…of: one item at a time

Most of the time you do not care about counting; you want to do something with each item in an array. The for…of loop does exactly that, and it is the loop you will use most:

for-of.js⤓ File
const prices = [12, 5, 30, 8];
let total = 0;

for (const price of prices) {
  total = total + price;
}

console.log(`Items: ${prices.length}`);
console.log(`Total: ${total}`);
console.log(`Average: ${total / prices.length}`);
Recorded output$ node for-of.js
Items: 4
Total: 55
Average: 13.75

9.4 The while loop

Sometimes you do not know in advance how many rounds you need. A while loop keeps going as long as a condition is true:

while.js⤓ File
let savings = 0;
let week = 0;
const goal = 100;

while (savings < goal) {
  week++;
  savings = savings + 15;
}

console.log(`Reached ${savings} after ${week} weeks`);
Recorded output$ node while.js
Reached 105 after 7 weeks

9.5 break and continue

Two words give you finer control inside any loop. break leaves the loop immediately. continue skips the rest of the current iteration and jumps to the next one:

break.js⤓ File
const scores = [72, 85, -1, 90, 64];

for (const score of scores) {
  if (score < 0) {
    console.log("Invalid score, stopping.");
    break;
  }
  if (score < 75) {
    continue;
  }
  console.log(`Great score: ${score}`);
}
Recorded output$ node break.js
Great score: 85
Invalid score, stopping.

9.6 Project: the kiosk serves a queue

Here is the kiosk from Chapter 8, now serving a whole line of visitors. Each number in queue is the age of one visitor. The pricing rules are the same; what is new is the loop around them, and three accumulators that build a total, a count and a receipt:

queue.js⤓ File
// Ages of the visitors waiting in line
const queue = [34, 9, 2, 70, 16, 41, 3];

let total = 0;
let freeTickets = 0;
const receipt = [];

for (const age of queue) {
  let price;
  if (age < 4) {
    price = 0;
    freeTickets++;
  } else if (age < 13 || age >= 65) {
    price = 6;
  } else {
    price = 10;
  }
  total = total + price;
  receipt.push(price);
}

console.log(`Visitors served: ${queue.length}`);
console.log(`Prices: ${receipt.join(", ")}`);
console.log(`Free tickets: ${freeTickets}`);
console.log(`Total: ${total}`);
Recorded output$ node queue.js
Visitors served: 7
Prices: 10, 6, 0, 6, 10, 10, 0
Free tickets: 2
Total: 42

Practice projects

Project 9.1 · Easy

Class statistics

A teacher has the scores of a whole class. In one pass through the list, find the average, the highest and lowest score, and how many students passed.

You will practise: for…of, several accumulators at once, and += and ++.

Steps
  1. Create an array of eight scores.
  2. Before the loop, create four accumulators: total starting at 0, highest and lowest starting at the first score, and passed starting at 0.
  3. In one for…of loop, update all four. total += score is short for total = total + score.
  4. After the loop, print the number of students, the average (total / scores.length), the highest, the lowest, and “passed out of total”.
  5. Add a score of 100 and one of 0 to the array, and check that the results change as you expect.

Hint: start highest and lowest at the first score, not at 0. If you start lowest at 0, it never changes, because no score is below 0.

Solution
class-stats.js⤓ File
const scores = [72, 95, 48, 83, 61, 90, 55, 77];

let total = 0;
let highest = scores[0];
let lowest = scores[0];
let passed = 0;

for (const score of scores) {
  total += score;
  if (score > highest) highest = score;
  if (score < lowest) lowest = score;
  if (score >= 50) passed++;
}

console.log("Students:", scores.length);
console.log("Average:", total / scores.length);
console.log("Highest:", highest);
console.log("Lowest:", lowest);
console.log("Passed:", passed, "/", scores.length);
Recorded output$ node class-stats.js
Students: 8
Average: 72.625
Highest: 95
Lowest: 48
Passed: 7 / 8

Project 9.2 · Medium

A shopping list without duplicates

Add new items to a shopping list, skipping any item that is already there, and print the list numbered from 1.

You will practise: includes, push, and the classic for loop with an index.

Steps
  1. Start with a list of two items, and an array toAdd of three items, one of which is already on the list.
  2. Loop over toAdd. If the list already includes the item, print a message; otherwise push it.
  3. Print the final list with a classic for loop, so that you have the index i to number each line.
  4. People count from 1, arrays from 0: print i + 1, not i.

Hint: “Bread” and “bread” are different strings for JavaScript. If users may type either, compare item.toLowerCase() instead.

Solution
shopping-list.js⤓ File
const list = ["bread", "milk"];

const toAdd = ["eggs", "bread", "tomatoes"];
for (const item of toAdd) {
  if (list.includes(item)) {
    console.log(`${item} is already on the list`);
  } else {
    list.push(item);
  }
}

console.log("Shopping list:");
for (let i = 0; i < list.length; i++) {
  console.log(`${i + 1}. ${list[i]}`);
}
Recorded output$ node shopping-list.js
bread is already on the list
Shopping list:
1. bread
2. milk
3. eggs
4. tomatoes

Project 9.3 · Challenge

The counting game and a triangle of stars

Two classic loop puzzles. First, count from 1 to 15, but say “Bit” for multiples of 3, “Bot” for multiples of 5, and “Bit Bot” for multiples of both. Second, draw a triangle of stars.

You will practise: % inside a loop, the order of conditions, and nested loops.

Steps
  1. Write a for loop from 1 to 15.
  2. Inside, check for “both” first: n % 3 === 0 && n % 5 === 0. Then 3 alone, then 5 alone, else the number itself.
  3. For the triangle, write an outer loop for the rows, 1 to 4. Inside it, start an empty string line.
  4. An inner loop adds "* " to the line once for each row number: row 1 gets one star, row 4 gets four.
  5. Print the line after the inner loop. Then change the program to draw 10 rows, or an upside-down triangle.

Hint: this counting game (usually called FizzBuzz) is a very common question in programming interviews. The trap is the order: if “3” is checked before “both”, 15 prints only “Bit”.

Solution
patterns.js⤓ File
// 1. The counting game: Bit for multiples of 3, Bot for 5, Bit Bot for both
for (let n = 1; n <= 15; n++) {
  if (n % 3 === 0 && n % 5 === 0) {
    console.log("Bit Bot");
  } else if (n % 3 === 0) {
    console.log("Bit");
  } else if (n % 5 === 0) {
    console.log("Bot");
  } else {
    console.log(n);
  }
}

// 2. A triangle of stars: a loop inside a loop
for (let row = 1; row <= 4; row++) {
  let line = "";
  for (let i = 0; i < row; i++) {
    line += "* ";
  }
  console.log(line);
}
Recorded output$ node patterns.js
1
2
Bit
4
Bot
Bit
7
8
Bit
Bot
11
Bit
13
14
Bit Bot
* 
* * 
* * * 
* * * *

Exercises

Exercise 9.1 · Easy

Print the multiplication table of 7, from 7 × 1 = 7 to 7 × 10 = 70.
The book's short answer
for (let i = 1; i <= 10; i++) { console.log(`7 × ${i} = ${7 * i}`); }
Show the solution
table-of-7.js⤓ File
for (let i = 1; i <= 10; i++) {
  console.log(`7 × ${i} = ${7 * i}`);
}
Recorded output$ node table-of-7.js
7 × 1 = 7
7 × 2 = 14
7 × 3 = 21
7 × 4 = 28
7 × 5 = 35
7 × 6 = 42
7 × 7 = 49
7 × 8 = 56
7 × 9 = 63
7 × 10 = 70

Exercise 9.2 · Easy

Make an array of five temperatures and print the highest and the lowest. (Hint: two accumulators.)
The book's short answer
Start highest and lowest at the first temperature; in a for…of, update each when a temperature is bigger or smaller.
Show the solution
temperatures.js⤓ File
const temperatures = [21, 27, 18, 31, 24];

// Two accumulators, both starting at the first temperature (not at 0: what if every day were below 0?).
let highest = temperatures[0];
let lowest = temperatures[0];

for (const t of temperatures) {
  if (t > highest) {
    highest = t;
  }
  if (t < lowest) {
    lowest = t;
  }
}

console.log(`Highest: ${highest}`);
console.log(`Lowest: ${lowest}`);
Recorded output$ node temperatures.js
Highest: 31
Lowest: 18

Exercise 9.3 · Medium

Given const words = ["code", "is", "fun", "and", "useful"], build a new array containing only the words longer than three letters, then print it joined with spaces.
The book's short answer
const long = []; for (const w of words) { if (w.length > 3) long.push(w); } console.log(long.join(" ")); gives code useful.
Show the solution
long-words.js⤓ File
const words = ["code", "is", "fun", "and", "useful"];
const long = [];

for (const w of words) {
  if (w.length > 3) {
    long.push(w);
  }
}

console.log(long.join(" "));
Recorded output$ node long-words.js
code useful

Exercise 9.4 · Medium

Count how many even numbers there are between 1 and 100, using a loop and %.
The book's short answer
50.
Show the solution
evens.js⤓ File
let count = 0;

for (let n = 1; n <= 100; n++) {
  if (n % 2 === 0) {
    count++;
  }
}

console.log(`Even numbers from 1 to 100: ${count}`);
Recorded output$ node evens.js
Even numbers from 1 to 100: 50

Exercise 9.5 · Challenge

Extend queue.js: if a visitor is 65 or older, also print “Senior discount applied”. At the end, print the average price and the most expensive ticket sold.
The book's short answer
Print the message inside the age >= 65 case; after the loop, divide total by queue.length, and keep a highest accumulator for the most expensive ticket.
Show the solution
queue.js⤓ File
// queue.js from the chapter, with a senior message, the average price and the most expensive ticket.
const queue = [34, 9, 2, 70, 16, 41, 3];

let total = 0;
let freeTickets = 0;
let highest = 0;
const receipt = [];

for (const age of queue) {
  let price;
  if (age < 4) {
    price = 0;
    freeTickets++;
  } else if (age < 13 || age >= 65) {
    price = 6;
    if (age >= 65) {
      console.log(`Age ${age}: Senior discount applied`);
    }
  } else {
    price = 10;
  }
  total = total + price;
  if (price > highest) {
    highest = price;
  }
  receipt.push(price);
}

console.log(`Visitors: ${queue.length}`);
console.log(`Prices: ${receipt.join(", ")}`);
console.log(`Free tickets: ${freeTickets}`);
console.log(`Total: ${total}`);
console.log(`Average price: ${(total / queue.length).toFixed(2)}`);
console.log(`Most expensive ticket: ${highest}`);
Recorded output$ node queue.js
Age 70: Senior discount applied
Visitors: 7
Prices: 10, 6, 0, 6, 10, 10, 0
Free tickets: 2
Total: 42
Average price: 6.00
Most expensive ticket: 10