Learn/JavaScript/7. Collections
Lesson 7 of 15
Sign in

JavaScript, lesson 7

Collections

One variable per value stops working once you have a whole class of test scores or a menu of prices. JavaScript's two everyday collections are the array, an ordered list, and the Map, which links keys to values. Plain objects can also act as small lookup tables.

Arrays

const keeps the variable pointing at the same array, but the array itself can still change, which is why push works here. Reading an index that does not exist gives undefined rather than an error.

Useful array methods:

MethodWhat it does
push(x) / pop()

2 exercises to try what you just read.

Exercise 1

Quiz statistics

Press Ctrl Enter or Check to test your code.

Exercise 2

Café menu

Press Ctrl Enter or Check to test your code.

add to / remove from the end
includes(x)true if x is in the array
indexOf(x)position of x, or -1
slice(a, b)a copy of elements from index a up to (not including) b
join(sep)one string with sep between the elements
map(fn)a new array with fn applied to each element

map is handy for converting input: "3 9 4".split(" ").map(Number) gives [3, 9, 4]. You will explore map and its friends properly in the closures lesson.

Math.max and Math.min take separate arguments, not an array. The spread syntax ... unpacks an array into arguments: Math.max(...scores).

Objects as records

An object groups named values, called properties:

Use dot notation when you know the name in advance, and brackets when the name is in a variable: book[field].

Map for lookups

When keys come from data, such as product names read from input, use a Map. It is designed for adding, finding and removing entries by key:

A Map remembers insertion order, accepts any value as a key (numbers, even objects), and has a size property. Plain objects only use string keys and inherit some built-in property names, so a Map is the safer choice for data-driven keys.

The for (const [item, price] of prices) line uses destructuring: each entry is a two-element array [key, value], and the brackets unpack it into two variables. Destructuring works on any array: const [first, second] = lines;.

Further reading

  • MDN: Indexed collections (arrays)
  • MDN: Keyed collections (Map and Set)
  • MDN: Working with objects
  • MDN: Destructuring

The input is one line of whole-number quiz scores separated by spaces (at least one score). Print three lines: the highest score, the lowest score, and the average rounded to one decimal place.

Sample input:

Sample output:

The first line of input is a number N. The next N lines each hold a menu item and its price, like latte 3.20. After that, every remaining line is a customer's order: one item name. For each order print ITEM: PRICE with the price shown to two decimals, or ITEM: not on the menu if the café does not sell it.

Sample input:

Sample output:

Store the menu in a Map.

const scores = [72, 95, 88];

console.log(scores[0]);       // 72 (indexes start at 0)
console.log(scores.length);   // 3
console.log(scores.at(-1));   // 88 (negative index counts from the end)

scores.push(64);              // add to the end
scores[1] = 99;               // replace an element
console.log(scores);          // [ 72, 99, 88, 64 ]
const book = { title: "Dune", year: 1965, pages: 412 };
console.log(book.title);        // Dune
console.log(book["year"]);      // 1965
book.pages = 600;               // change a property
book.rating = 5;                // add a new one
const prices = new Map();
prices.set("tea", 2.5);
prices.set("cake", 4);

console.log(prices.get("tea"));     // 2.5
console.log(prices.has("coffee"));  // false
console.log(prices.get("coffee"));  // undefined
console.log(prices.size);           // 2

for (const [item, price] of prices) {
  console.log(`${item}: ${price}`);
}
72 95 88 64
max 95
min 64
avg 79.8
2
latte 3.20
muffin 2.75
muffin
tea
muffin: 2.75
tea: not on the menu