Skip to content
HopperHopper

Course navigation

Phase 2 · Data and functionsDay 6

Arrays and tuples

  • About 70 minutes
  • 10 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 70 minutes

Section 1 of 10

6.1 Array Literals and Array Types

Before you start, set up a new project folder named day06 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.

Every variable so far has held one value: one score, one name, one boolean. But most data comes in groups. A class has thirty scores, not one; a shopping list has a dozen items; a week has seven days. With only single variables, a program for thirty scores would need score1 up to score30, and a loop could not visit them, because a loop needs something it can count through. On Day 3 you met the answer in passing: split gave back an array, one value that holds several values in order. Today arrays get their full day.

The simplest way to make an array is to write its values between square brackets, separated by commas. This is an array literal, just as "Lima" is a string literal and 42 a number literal. Each value inside is called an element.

Worked example: A list in one variable

shopping-list.ts
const shoppingList = ["eggs", "milk", "bread"];
console.log(shoppingList);
console.log(shoppingList.length);
const scores: number[] = [88, 92, 79];
console.log(scores);
const empty: string[] = [];
console.log(empty, empty.length);
[ 'eggs', 'milk', 'bread' ]
3
[ 88, 92, 79 ]
[] 0

Line 1 stores three strings in one variable. Line 2 shows how Node prints an array: square brackets, the elements separated by commas, and strings in single quotes (that is only Node’s way of showing them; they are ordinary strings). Line 3 shows that an array has a length property, the number of elements, just as a string has. Line 4 stores three numbers, and line 6 makes an array with no elements at all: [], with length 0.

What type does the checker give an array? Hover over shoppingList and VS Code shows const shoppingList: string[]: the element type followed by [], read “an array of strings.” Line 1 has no annotation, so this is Day 2’s type inference at work: every element in the literal is a string, so the array is a string[]. In the same way, [88, 92, 79] is inferred as number[], and [true, false] as boolean[]. The [] in a type is different from the [] in a literal: in number[] it means “array of,” and in [88, 92] it holds the elements.

Line 4 writes the annotation anyway, const scores: number[], which you may do whenever you want to state the type. Line 6 must write one: an empty literal [] has no elements to infer from, so without the annotation the checker cannot tell what the array will hold. Make it a habit: an empty array always gets an annotation.

An array is one value, so a variable holds it the way it holds a string. But its type is new to typeof:

typeof-array.ts
const scores = [88, 92, 79];
console.log(typeof scores);
console.log(Array.isArray(scores));
console.log(typeof scores[0]);
object
true
number

typeof reports "object" for an array, the same word it gave for null on Day 2; it has no separate word for arrays. Line 3 shows the way to ask: Array.isArray(value) is true only for an array. Line 4 asks about one element, scores[0], and that is a number.

Key idea

An array literal [88, 92, 79] holds several values, its elements, in order. The checker infers its type from the elements, number[] or string[], read “array of.” An empty array [] needs an annotation, such as const scores: number[] = [];. Node prints an array in square brackets.

Watch out

An element of the wrong type. The element type is a rule for every element. With an annotation, the checker holds each element to it:

wrong-element.ts
const scores: number[] = [88, 92, "79"];
console.log(scores);
wrong-element.ts:1:35 - error TS2322: Type 'string' is not assignable to type 'number'.

This is Day 1’s TS2322, and column 35 is the "79": a string where a number was promised. Take the quotes off, or delete the file. Without the annotation, the checker does something less helpful. Take the annotation away, and it infers the type of [88, 92, "79"] as (string | number)[], read “an array of values that are each a string or a number.” (Types joined with | are Day 9’s topic.) No error appears on line 1, but the mixed type follows every element around:

mixed-list.ts
const scores = [88, 92, "79"];
console.log(scores[2] + 1);
mixed-list.ts:2:13 - error TS2365: Operator '+' cannot be applied to types 'string | number' and 'number'.

The checker no longer knows whether scores[2] is a number, so it will not let you add to it. A stray pair of quotes in a long literal is easy to miss, so annotate an array whenever its elements should all share one type. Fix or delete mixed-list.ts before your next check.

Pause and try

Question 1 · Tracing

Predict exactly what this program shows, and say what type the checker gives each array.

predict-array.ts
const cities = ["Lima", "Oslo"];
const populations: number[] = [];
console.log(cities.length, populations.length);
console.log(cities);
console.log(populations);
console.log(typeof cities[1]);
Check your reasoning
2 0
[ 'Lima', 'Oslo' ]
[]
string

cities is inferred as string[] from its two string elements. populations is annotated number[], which it has to be, because [] gives the checker nothing to infer from. An empty array prints as []. Line 6 asks about one element, cities[1], which is the string "Oslo", so typeof gives string; typeof cities itself would be object.

Reread 6.1 Array Literals and Array Types if any line differed.

Question 2 · Multiple choice

Which declaration does npx tsc reject?

  1. const names: string[] = [];
  2. const names = ["Ana", "Ben"];
  3. const ages: number[] = [12, "13"];
  4. const flags = [true, false, true];
Check your reasoning

C. The annotation number[] promises that every element is a number, and "13" is a string: TS2322.

  • A is wrong: an empty array with an annotation is exactly right. It is the one case where the annotation is required.
  • B is wrong: the checker infers string[] from the two strings.
  • D is wrong: the checker infers boolean[].

Reread 6.1 Array Literals and Array Types if you chose differently.

Section 2 of 10

6.2 Indexing and Length

Storing thirty scores in one array is only useful if you can get one of them back out. A program needs the first score, the last score, or the score at some position worked out while it runs.

Arrays use the same positions as strings. Each element has an index, its position counted from 0: the first element is at index 0, the second at index 1, and the last at length - 1. Everything you learned in 3.4 about a string’s characters applies to an array’s elements:

  • items[i] gives the element at index i. Square brackets after a value are the indexing operation.
  • items.at(i) gives the same element, and also accepts a negative index that counts from the end: at(-1) is the last element.
  • items.length is the number of elements, so the last index is items.length - 1.

Worked example: Reading temperatures by position

indexing-array.ts
const temps = [21, 24, 19, 27];
console.log(temps[0]);
console.log(temps[3]);
console.log(temps[temps.length - 1]);
console.log(temps.at(-1));
console.log(temps.at(-2));
console.log(temps[4]);
console.log(temps[-1]);
21
27
27
27
19
undefined
undefined
Line Expression Worked out Value
2 temps[0] The first element 21
3 temps[3] Three elements come before it: 21, 24, 19 27
4 temps[temps.length-1] temps[4 - 1], which is temps[3] 27
5 temps.at(-1) The last element, counted from the end 27
6 temps.at(-2) The second to last 19
7 temps[4] No element has index 4 undefined
8 temps[-1] Square brackets do not count from the end undefined

Lines 7 and 8 ask for positions that do not exist, and the answer is Day 2’s undefined, “no value here.” Nobody reports an error, exactly as with a string.

The checker treats these two tools differently, and in the same way as for strings. temps[i] has the type number for every i, because the checker does not work out which indexes exist. temps.at(i) has the type number | undefined, because the checker knows at can run off the end; you can show that value, but you cannot do arithmetic with it or call a method on it until Day 9 shows how to check it. So reading past the end with square brackets is a mistake that only shows up when the program runs:

past-the-end.ts
const names = ["Ana", "Ben", "Cleo"];
const fourth = names[3];
console.log(fourth);
console.log(fourth.toUpperCase());

npx tsc reports no errors for this file, but node past-the-end.ts shows:

undefined
TypeError: Cannot read properties of undefined (reading 'toUpperCase')

Three names have indexes 0, 1, and 2, so names[3] is one past the end: an off-by-one error. Line 3 shows undefined, and line 4 tries to call a method on it, which is the runtime error from Day 1 and Day 3. The checker believed fourth was a string and could not warn you. Whenever you write an index, ask “how many elements come before the one I want?”, and remember that the last one is at length - 1.

Key idea

items[i] and items.at(i) give the element at index i; indexes start at 0, the last is length - 1, and at(-1) counts from the end. A position that does not exist gives undefined, which the checker does not catch for square brackets.

Pause and try

Question 3 · Tracing

Predict exactly what this program shows.

predict-index.ts
const stops = ["Park", "Mall", "Station", "Harbor"];
console.log(stops[1]);
console.log(stops.at(-1));
console.log(stops[stops.length]);
console.log(stops.length - 1);
console.log(stops[0].length);
Check your reasoning
Mall
Harbor
undefined
3
4
  • Line 2: index 1 is the second element, Mall.
  • Line 3: at(-1) is the last element, Harbor.
  • Line 4: stops.length is 4, and index 4 is one past the last index, 3: undefined.
  • Line 5: 4 - 1 is 3, the last index itself.
  • Line 6: stops[0] is the string "Park", and its length is 4 characters. The first .length you write today may be an array’s or a string’s; read the value before the dot to tell which.

Reread 6.2 Indexing and Length if any line differed.

Section 3 of 10

6.3 Changing an Array

On Day 3 you learned that a string can never be changed: greeting[0] = "J" was rejected with TS2542, and every string method gave back a new string. A list is different. A shopping list gets items added and crossed off all day, and copying the whole list every time would be wasteful. So arrays are mutable: the elements of an existing array can be changed in place.

The simplest change is to assign to an index, the very thing strings forbid:

change-item.ts
const letters = ["h", "e", "l", "l", "o"];
letters[0] = "J";
console.log(letters);
console.log(letters.join(""));
[ 'J', 'e', 'l', 'l', 'o' ]
Jello

Line 2 replaces the element at index 0, and the same array now holds "J" first. Line 4 uses Day 3’s join("") to glue the elements into one string, with nothing between them. Compare that with change-letter.ts from 3.7: the string version was rejected; the array version is the normal way to work.

Four methods change the length of an array, two at each end. Think of the array as a line of people: the end is the back of the line (the highest index), and the start is the front (index 0).

Method What it does Gives back
items.push(x) Adds x at the end The new length
items.pop() Removes the last element The removed element
items.unshift(x) Adds x at the start (everything moves up) The new length
items.shift() Removes the first element (everything moves down) The removed element

push and unshift accept more than one value: items.push("a", "b") adds both, in that order.

Worked example: A waiting list

queue.ts
const waiting = ["Ana", "Ben"];
const count = waiting.push("Cleo");
console.log(waiting, count);
waiting.unshift("Zed");
console.log(waiting);
const served = waiting.shift();
console.log(served, waiting);
const left = waiting.pop();
console.log(left, waiting);
[ 'Ana', 'Ben', 'Cleo' ] 3
[ 'Zed', 'Ana', 'Ben', 'Cleo' ]
Zed [ 'Ana', 'Ben', 'Cleo' ]
Cleo [ 'Ana', 'Ben' ]
Line Call waiting afterwards Gives back
2 waiting.push("Cleo") [ 'Ana', 'Ben', 'Cleo' ] 3
4 waiting.unshift("Zed") [ 'Zed', 'Ana', 'Ben', 'Cleo' ] 4
6 waiting.shift() [ 'Ana', 'Ben', 'Cleo' ] "Zed"
8 waiting.pop() [ 'Ana', 'Ben' ] "Cleo"

Every call changes waiting itself; nothing needs to be stored back into it. Line 2 stores what push gives back, the new length 3, in count. Lines 6 and 8 store the removed elements. Hover over served and VS Code shows const served: string | undefined: like at, shift and pop might find the array empty, so the checker gives their result the “or undefined” type. Show it, as here, but do not call a method on it until Day 9.

Now vary one thing: pop from an array that is already empty.

pop-empty.ts
const stack: number[] = [];
const top = stack.pop();
console.log(top, stack.length);
undefined 0

There is nothing to remove, so pop gives undefined and the array stays empty; no error is reported. That is why the checker types the result as number | undefined.

What about const? Every array above was declared with const, and every one was changed. There is no contradiction. A const means the variable can never be given a different value; it says nothing about changing the value it already holds. The array is one value, a container, and push changes what is in the container without replacing it.

const-list.ts
const list = ["a"];
list.push("b");
list[0] = "A";
console.log(list);
[ 'A', 'b' ]

Both line 2 and line 3 change the array that list holds, and npx tsc reports no errors. Giving list a different array is what const forbids:

const-list-reassign.ts
const list = ["a"];
list = ["b"];
console.log(list);
const-list-reassign.ts:2:1 - error TS2588: Cannot assign to 'list' because it is a constant.

This is Day 2’s TS2588: = tries to replace the whole value in list. Fix or delete the file. The rule of thumb: use const for an array unless the variable itself will be pointed at a new array later.

Key idea

Arrays are mutable. items[i] = x replaces one element; push and pop add and remove at the end; unshift and shift add and remove at the start. push and unshift give back the new length; pop and shift give back the removed element, typed “or undefined.” A const array can be changed, but not replaced.

Watch out

Storing what push gives back. It is natural to expect a method to give back the new array, as string methods did:

push-result.ts
const list = ["a", "b"];
const bigger = list.push("c");
console.log(bigger);
3

push changes list in place and gives back the new length, so bigger is the number 3, not an array. Neither npx tsc nor node reports anything. Call push for its effect and keep using list.

Pause and try

Question 4 · Tracing

Predict exactly what this program shows. Write out the array after each line.

predict-queue.ts
const line = ["Ana", "Ben"];
line.push("Cleo", "Dan");
line.shift();
line.unshift("Eve");
const last = line.pop();
console.log(line);
console.log(last, line.length);
Check your reasoning
[ 'Eve', 'Ben', 'Cleo' ]
Dan 3
Line Call line afterwards
2 push("Cleo", "Dan") [ 'Ana', 'Ben', 'Cleo', 'Dan' ]
3 shift() [ 'Ben', 'Cleo', 'Dan' ]
4 unshift("Eve") [ 'Eve', 'Ben', 'Cleo', 'Dan' ]
5 pop() [ 'Eve', 'Ben', 'Cleo' ]

Line 5 stores the removed "Dan" in last, and the array is left with three elements.

Reread 6.3 Changing an Array if any line differed.

Question 5 · Multiple choice

const cart = ["pen"]; has been declared. Which line does npx tsc reject?

  1. cart.push("ink");
  2. cart[0] = "pencil";
  3. cart = ["pen", "ink"];
  4. cart.pop();
Check your reasoning

C. = replaces the whole value in cart, and a const variable can never be assigned again: TS2588.

  • A and D are wrong: they change the array that cart already holds, which const allows.
  • B is wrong: assigning to an index changes one element of the same array. Only strings forbid that.

Reread 6.3 Changing an Array if you chose differently.

Section 4 of 10

6.4 Inserting and Removing with splice

push, pop, shift, and unshift only work at the two ends. To take the third song out of a playlist, or to slip two songs in after the first, you need to change the middle of an array. One method does both jobs: splice.

items.splice(start, deleteCount, newItem1, newItem2, ...)
Piece What it is
start The index where the change begins
deleteCount How many elements to remove from there; 0 removes none
new items Any values to insert at start, after the removal; leave them out to insert nothing

splice changes the array in place and gives back an array of the removed elements (empty if none).

Worked example: Taking a song out

splice-remove.ts
const playlist = ["Intro", "Sunrise", "Static", "Outro"];
const removed = playlist.splice(2, 1);
console.log(removed);
console.log(playlist);
[ 'Static' ]
[ 'Intro', 'Sunrise', 'Outro' ]

Line 2 starts at index 2, the third song, and removes one element. removed holds the removed elements as an array, [ 'Static' ], even though there is only one. The elements after the gap move down, so "Outro" is now at index 2.

Now vary it: a deleteCount of 0 removes nothing, so splice only inserts; and removing one while inserting another replaces it.

splice-insert.ts
const playlist = ["Intro", "Sunrise", "Outro"];
playlist.splice(1, 0, "Dawn", "Morning");
console.log(playlist);
playlist.splice(0, 2, "Opening");
console.log(playlist);
[ 'Intro', 'Dawn', 'Morning', 'Sunrise', 'Outro' ]
[ 'Opening', 'Morning', 'Sunrise', 'Outro' ]

Line 2 inserts two songs at index 1, pushing "Sunrise" and "Outro" up to make room. Line 4 starts at index 0, removes two elements ("Intro" and "Dawn"), and puts "Opening" in their place.

Key idea

items.splice(start, deleteCount, ...newItems) removes deleteCount elements at index start, inserts any new items there, and gives back an array of what it removed. It changes the array in place.

Watch out

Leaving out the count. splice with only a start index removes everything from there to the end:

splice-rest.ts
const playlist = ["Intro", "Sunrise", "Static", "Outro"];
playlist.splice(1);
console.log(playlist);
[ 'Intro' ]

The writer meant to remove one song at index 1, but without a deleteCount, splice(1) removed the three songs from index 1 onward. Nothing reports it. To remove one element, always write the count: splice(1, 1).

Assigning past the end. Index assignment can also change the length, and not in a helpful way:

holes.ts
const seats = ["Ana", "Ben"];
seats[4] = "Eve";
console.log(seats);
console.log(seats.length);
console.log(seats[2]);
[ 'Ana', 'Ben', <2 empty items>, 'Eve' ]
5
undefined

Two seats had indexes 0 and 1, and line 2 writes to index 4. JavaScript allows it, and fills the gap with two empty slots, which read as undefined; the length jumps to 5. The checker allows it too, because it does not track which indexes exist. To add at the end, use push; to put something at a particular index, make sure that index exists first.

Pause and try

Question 6 · Tracing

Predict exactly what this program shows.

predict-splice.ts
const steps = ["wake", "eat", "code", "sleep"];
const out = steps.splice(1, 2, "run");
console.log(out);
console.log(steps);
steps.splice(steps.length, 0, "dream");
console.log(steps);
Check your reasoning
[ 'eat', 'code' ]
[ 'wake', 'run', 'sleep' ]
[ 'wake', 'run', 'sleep', 'dream' ]
  • Line 2: start at index 1, remove two elements ("eat" and "code"), and insert "run" there. out holds the two removed elements.
  • Line 5: start at index 3, which is steps.length, one past the last element, and remove nothing. Inserting there is the same as push("dream").

Reread 6.4 Inserting and Removing with splice if any line differed.

Section 5 of 10

6.5 Copying an Array

Suppose a program keeps the original list of entrants in a race and also needs a working list to cross people off as they finish. The obvious move is const working = entrants;. It does not do what it looks like, and the reason is the most important idea of the day.

A variable holding a string holds the string itself; copy it into another variable and you have two strings. A variable holding an array holds a reference: a way of pointing at the one array stored in the computer’s memory. Assigning that variable to another copies the reference, not the array. Now two names point at the same container, and a change made through either name is seen through both.

Worked example: Two names, one array

shared-list.ts
const original = ["Ana", "Ben"];
const alias = original;
alias.push("Cleo");
console.log(original);
console.log(alias === original);
[ 'Ana', 'Ben', 'Cleo' ]
true
Name Points at
original the array in memory
alias the same array

Line 3 pushes through alias, and line 4 shows original: it has three elements, because there is only one array. Line 5 confirms it: === between two arrays asks “are these the same array?”, and here the answer is true.

To get a separate array with the same elements, you have to ask for a copy. Day 3’s slice works on arrays too: items.slice(start, end) gives back a new array holding the elements from start up to but not including end, with the same negative-index and left-out-argument rules as for strings. With no arguments at all, slice() copies the whole array:

copy-list.ts
const original = ["Ana", "Ben"];
const copy = original.slice();
copy.push("Cleo");
console.log(original);
console.log(copy);
console.log(copy === original);
[ 'Ana', 'Ben' ]
[ 'Ana', 'Ben', 'Cleo' ]
false

Now there are two arrays. Pushing to copy leaves original with two elements, and === on line 6 is false: same elements, different arrays. Here is slice taking parts, exactly as in 3.5:

slice-part.ts
const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
console.log(days.slice(1, 3));
console.log(days.slice(3));
console.log(days.slice(-2));
console.log(days);
[ 'Tue', 'Wed' ]
[ 'Thu', 'Fri' ]
[ 'Thu', 'Fri' ]
[ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' ]

slice(1, 3) takes indexes 1 and 2; slice(3) takes from index 3 to the end; slice(-2) takes the last two. Line 5 shows that days is untouched: unlike splice, which changes the array, slice only copies from it. The names differ by one letter, so read them carefully.

The second way to copy is newer and more flexible. Inside an array literal, ...items means “every element of items, written out here.” The three dots are the spread operator, and they let you copy, join, and extend arrays in one expression:

spread.ts
const morning = ["Yoga", "Swim"];
const evening = ["Run"];
const copy = [...morning];
const all = [...morning, ...evening];
const withLunch = [...morning, "Lunch", ...evening];
console.log(copy);
console.log(all);
console.log(withLunch);
console.log(morning);
[ 'Yoga', 'Swim' ]
[ 'Yoga', 'Swim', 'Run' ]
[ 'Yoga', 'Swim', 'Lunch', 'Run' ]
[ 'Yoga', 'Swim' ]
Line Literal What it builds
3 [...morning] A new array with the two elements of morning
4 [...morning, ...evening] The elements of both, one after the other
5 [...morning, "Lunch", ...evening] Spread elements and plain values mixed in any order

Each literal makes a brand-new array, and line 9 shows morning unchanged. [...items] and items.slice() both copy; use spread when you also want to add or join, and either one when you just want a copy.

Key idea

A variable holds a reference to an array, so const alias = original; gives one array two names, and === compares references, not elements. items.slice() and [...items] make a new array with the same elements; [...a, ...b] joins two.

Watch out

Comparing arrays with ===. Because === compares references, two separate arrays are never equal, even when their elements match. The checker catches the literal case:

compare-literals.ts
console.log([1, 2] === [1, 2]);
compare-literals.ts:1:13 - error TS2839: This condition will always return 'false' since JavaScript compares objects by reference, not value.

Two literals are two arrays, so the comparison can never be true, and the message says why. With variables, the checker cannot know whether they point at the same array, so it stays quiet:

compare-arrays.ts
const a = [1, 2];
const b = [1, 2];
console.log(a === b);
console.log(a.join(",") === b.join(","));
false
true

a and b are different arrays, so line 3 is false. One honest way to compare the contents, with today’s tools, is line 4: join each into a string and compare the strings. Fix or delete compare-literals.ts before your next check.

Expecting reverse to give a new array. Day 3 used reverse() after split, where it did no harm. On an array you keep, it is a change in place:

reverse-in-place.ts
const steps = ["wake", "eat", "code"];
const backwards = steps.reverse();
console.log(steps);
console.log(backwards === steps);
[ 'code', 'eat', 'wake' ]
true

reverse turns steps around and gives back a reference to that same array, so backwards === steps is true and the original order is gone. To keep the original, reverse a copy:

reverse-copy.ts
const steps = ["wake", "eat", "code"];
const backwards = [...steps].reverse();
console.log(steps);
console.log(backwards);
[ 'wake', 'eat', 'code' ]
[ 'code', 'eat', 'wake' ]

Pause and try

Question 7 · Tracing

Predict exactly what this program shows. Decide first how many arrays there are.

predict-copy.ts
const base = [1, 2, 3];
const same = base;
const fresh = [...base];
same.push(4);
fresh.pop();
console.log(base);
console.log(same);
console.log(fresh);
console.log(same === base, fresh === base);
Check your reasoning
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2 ]
true false

There are two arrays. same is another name for the array base holds; fresh is a copy made by spread. Line 4 pushes 4 onto the shared array, so both base and same show it. Line 5 pops from the copy only. On line 9, same === base is true (one array) and fresh === base is false (a different array).

Reread 6.5 Copying an Array if any line differed.

Question 8 · Multiple choice

const todo = ["wash", "cook"]; has been declared. Which line does not make a new array?

  1. const a = [...todo];
  2. const b = todo.slice();
  3. const c = todo;
  4. const d = [...todo, "rest"];
Check your reasoning

C. c = todo copies the reference, so c and todo are two names for one array; a push through either is seen through both.

  • A and B are wrong: spread and slice() each build a new array with the same elements.
  • D is wrong: it builds a new array with three elements, leaving todo with two.

Reread 6.5 Copying an Array if you chose differently.

Section 6 of 10

6.6 Searching an Array

Before adding a guest to a list, a program should check whether the guest is already on it. Before removing a guest by name, it needs the index where that name sits. Day 3’s two search methods for strings, from 3.8, exist for arrays too, and they ask the same questions about elements instead of characters:

  • items.includes(x) is true when some element is strictly equal (===) to x, and false otherwise.
  • items.indexOf(x) is the index of the first element equal to x, or -1 when there is none.

Worked example: Is Ben on the list?

search.ts
const guests = ["Ana", "Ben", "Cleo"];
console.log(guests.includes("Ben"));
console.log(guests.includes("ben"));
console.log(guests.indexOf("Cleo"));
console.log(guests.indexOf("Dan"));
true
false
2
-1

Line 3 is false because includes uses ===, and "ben" is not the same string as "Ben". Line 4 finds "Cleo" at index 2. Line 5 finds no "Dan", so the answer is -1, the same “not found” signal as for strings.

Now put both to work with an if. The first check stops a duplicate; the second finds where a guest is, so splice can remove them:

rsvp.ts
const guests = ["Ana", "Ben", "Cleo"];
const newGuest: string = "Ben";
if (guests.includes(newGuest)) {
  console.log(`${newGuest} is already on the list.`);
} else {
  guests.push(newGuest);
}
const leaving: string = "Ana";
const position = guests.indexOf(leaving);
if (position !== -1) {
  guests.splice(position, 1);
}
console.log(guests);
Ben is already on the list.
[ 'Ben', 'Cleo' ]

Line 3 asks the yes-or-no question, and the else block only runs for a name that is new. Lines 9 to 12 are the pattern for removing an element by value: find its index, and if it was found (!== -1), splice one element out at that index. Without the if, a missing name would give -1, and splice(-1, 1) would remove the last element, because splice counts a negative start from the end just as slice does.

The checker helps with searches too. includes and indexOf only accept a value of the array’s element type:

includes-wrong-type.ts
const ids = [101, 102, 103];
console.log(ids.includes("102"));
includes-wrong-type.ts:2:26 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

TS2345 is the message for an argument, a value passed in the parentheses of a method, that has the wrong type. The array holds numbers, and no number is ever === to the string "102", so the search could never succeed; this is Day 4’s “no overlap” idea applied to a method. Fix it with ids.includes(102), or delete the file.

Key idea

items.includes(x) gives true or false; items.indexOf(x) gives the first index or -1. Both compare with === and accept only the element type. To remove by value: find the index, check it is not -1, then splice(index, 1).

Watch out

Putting indexOf straight into a condition. The “not found” answer is -1, and 4.8 taught that -1 is truthy:

index-of-truthy.ts
const guests = ["Ana", "Ben"];
if (guests.indexOf("Zed")) {
  console.log("Zed is on the list");
}
if (guests.indexOf("Ana")) {
  console.log("Ana is on the list");
}
Zed is on the list

Both results are backwards. indexOf("Zed") is -1, which is truthy, so the block runs. indexOf("Ana") is 0, the one falsy number, so Ana’s block is skipped even though she is first on the list. Neither npx tsc nor node reports anything. For a yes-or-no question, use includes; use indexOf when you need the position, and compare it with -1.

Pause and try

Question 9 · Tracing

Predict exactly what this program shows.

predict-search.ts
const codes = [12, 7, 12, 30];
console.log(codes.indexOf(12));
console.log(codes.indexOf(13));
console.log(codes.includes(30));
console.log(codes.includes(12) && codes.indexOf(7) === 1);
Check your reasoning
0
-1
true
true
  • Line 2: 12 appears twice, and indexOf gives the first index, 0.
  • Line 3: there is no 13: -1.
  • Line 4: 30 is the last element: true.
  • Line 5: includes(12) is true, and indexOf(7) is 1, so 1 === 1 is true; true && true is true.

Reread 6.6 Searching an Array if any line differed.

Section 7 of 10

6.7 Looping over an Array

An array of thirty scores is only useful if the program can visit all thirty: add them up, find the highest, count the passes. That is a loop’s job, and the loops from Day 5 work on arrays as they did on strings.

A for...of loop visits each element in order, from index 0 to the last, and gives it a name for one pass of the loop body. On Day 5 the loop variable held one character; here it holds one element, with the array’s element type. The accumulator patterns are the same too: a let declared before the loop, updated on each pass.

Worked example: Total, average, and highest

total-scores.ts
const scores = [88, 92, 79, 95];
let total = 0;
let highest = scores[0];
for (const score of scores) {
  total += score;
  if (score > highest) {
    highest = score;
  }
}
console.log(`Total: ${total}`);
console.log(`Average: ${(total / scores.length).toFixed(1)}`);
console.log(`Highest: ${highest}`);
Total: 354
Average: 88.5
Highest: 95
Pass score total after highest after
1 88 88 88
2 92 180 92
3 79 259 92
4 95 354 95

Line 3 starts highest at the first element, scores[0], as Day 5’s maximum pattern did with a string’s first character; starting at 0 would be wrong for an array of negative temperatures. Line 11 divides the total by scores.length, the number of elements, and toFixed(1) rounds the average to one decimal place.

Now vary the loop. When you need each element’s index as well, such as to number a list, use a counting for loop from 0 to length - 1 and index the array inside it:

numbered-list.ts
const tasks = ["Buy milk", "Walk the dog", "Read"];
for (let i = 0; i < tasks.length; i++) {
  console.log(`${i + 1}. ${tasks[i]}`);
}
1. Buy milk
2. Walk the dog
3. Read

i runs from 0 to 2, tasks[i] is the element at that index, and i + 1 turns the zero-based index into the one-based number a person expects. (6.10 shows a neater way to get the index and the element together.)

A loop can also build a new array. Start with an empty, annotated array, and push into it on the passes that qualify:

build-list.ts
const scores = [88, 52, 79, 95, 61];
const passing: number[] = [];
for (const score of scores) {
  if (score >= 60) {
    passing.push(score);
  }
}
console.log(passing);
console.log(`${passing.length} of ${scores.length} passed`);
[ 88, 79, 95, 61 ]
4 of 5 passed

Each passing score is pushed in the order it was met, so passing keeps the original order with the failing score left out. This “loop, test, push” pattern is how you filter a list with today’s tools.

Key idea

for (const item of items) visits each element in order; use a counting for with items[i] when you need the index. Accumulate with a let declared before the loop, and build a new array by pushing into an empty annotated one.

Watch out

Changing an array while looping over it. for...of walks through the array by index as it goes. Remove elements during the walk, and the elements shift under it:

remove-while-looping.ts
const queue = ["a", "b", "c", "d"];
for (const item of queue) {
  console.log(item);
  queue.shift();
}
console.log(queue);
a
c
[ 'c', 'd' ]

The first pass shows "a" and shifts it off, so "b" moves to index 0. The second pass moves on to index 1, which is now "c"; "b" is never visited. After shifting again, only two elements remain, so a third pass at index 2 finds nothing and the loop ends. Nothing is reported. Loop over a copy (for (const item of [...queue])) when the body changes the array, or build a new array instead of removing from the old one.

Pause and try

Question 10 · Tracing

Predict exactly what this program shows.

predict-loop.ts
const prices = [4, 10, 7];
let count = 0;
let sum = 0;
for (const price of prices) {
  if (price >= 5) {
    count++;
    sum += price;
  }
}
console.log(count, sum);
for (let i = prices.length - 1; i >= 0; i--) {
  console.log(prices[i]);
}
Check your reasoning
2 17
7
10
4

The first loop counts and sums the prices of at least 5: 10 and 7 qualify, 4 does not, so count is 2 and sum is 17. The second loop starts i at prices.length - 1, which is 2, and counts down to 0, so it shows the elements in reverse order: 7, 10, 4. A counting loop can run through the indexes in any order you like.

Reread 6.7 Looping over an Array if any line differed.

Section 8 of 10

6.8 readonly Arrays

Some lists must never change: the days of the week, the months, the fixed menu of a café. A const does not protect them, as 6.3 showed: it stops the variable being replaced, but push and index assignment still get through. What you want is for the checker to reject any line that tries to change the array.

Write readonly in front of the array type: readonly string[], read “a read-only array of strings.” A variable with that type still has every reading tool (length, indexing, at, includes, indexOf, slice, for...of), but the changing tools are gone.

Worked example: A list that only gets read

weekdays.ts
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
console.log(weekdays[0], weekdays.length);
console.log(weekdays.includes("Sat"));
for (const day of weekdays.slice(0, 2)) {
  console.log(day);
}
Mon 5
false
Mon
Tue

Everything here reads from weekdays: an index, the length, a search, and a loop over a slice. npx tsc reports no errors, because none of it changes the array. Now try to change it:

readonly-push.ts
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
weekdays.push("Sat");
console.log(weekdays);
readonly-push.ts:2:10 - error TS2339: Property 'push' does not exist on type 'readonly string[]'.

TS2339 means the value has no property or method by that name. From the checker’s point of view, a read-only array simply has no push (and no pop, shift, unshift, splice, or reverse). Assigning to an index is rejected too, with the message strings gave you on Day 3:

readonly-assign.ts
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
weekdays[0] = "Sun";
console.log(weekdays);
readonly-assign.ts:2:1 - error TS2542: Index signature in type 'readonly string[]' only permits reading.

Fix or delete both files before your next check.

readonly is a word the checker understands; Node strips it away with the rest of the types. Run readonly-push.ts with node anyway, and the push succeeds, because at run time it is an ordinary array. The protection comes entirely from running npx tsc first, which is why this course always does.

When you do need a changeable version, copy the elements into a new array. A spread literal [...weekdays] builds a plain string[], and the original stays protected:

readonly-copy.ts
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const schedule = [...weekdays];
schedule.push("Sat");
console.log(schedule);
console.log(weekdays);
[ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]
[ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' ]

What you cannot do is hand the same array to a mutable name, because that would be a back door:

readonly-to-mutable.ts
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const schedule: string[] = weekdays;
console.log(schedule);
readonly-to-mutable.ts:2:7 - error TS4104: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.

If this were allowed, schedule.push("Sat") would change the one array that weekdays promised never to change. Copy instead, as above, then fix or delete this file.

Key idea

readonly string[] is an array type the checker will only let you read: push, pop, shift, unshift, splice, reverse, and index assignment are rejected. Node does not enforce it. Copy with [...items] to get a changeable string[].

Pause and try

Question 11 · Multiple choice

const sizes: readonly string[] = ["S", "M", "L"]; has been declared. Which line does npx tsc accept?

  1. sizes.push("XL");
  2. sizes[0] = "XS";
  3. const bigger = [...sizes, "XL"];
  4. const all: string[] = sizes;
Check your reasoning

C. Spread reads the elements into a brand-new, ordinary array, and reading is allowed; sizes is unchanged.

  • A is wrong: a read-only array has no push (TS2339).
  • B is wrong: its index signature only permits reading (TS2542).
  • D is wrong: a read-only array cannot be given a mutable type (TS4104), because all.push would then change sizes.

Reread 6.8 readonly Arrays if you chose differently.

Section 9 of 10

6.9 Tuples

An array holds any number of elements of one type. Some data has a different shape: a fixed number of values, each with its own meaning and perhaps its own type. A test result is a name and a score, ["Ana", 92]. A point on a map is a latitude and a longitude. A product line is a name, a price, and whether it is in stock. The pairs and triples always have the same positions, and position 0 is not the same kind of thing as position 1.

Look at what inference makes of such a pair:

inferred-pair.ts
const entry = ["Ana", 92];
console.log(entry[1] + 5);
inferred-pair.ts:2:13 - error TS2365: Operator '+' cannot be applied to types 'string | number' and 'number'.

Given ["Ana", 92], the checker infers (string | number)[]: an array of any length, where each element might be a string or might be a number. It has forgotten that position 1 is always the score. So entry[1] + 5 is rejected, as in 6.1’s mixed-list.ts. Fix or delete this file.

A tuple type says exactly what you mean: a fixed-length array where each position has its own type. Write it as the types in square brackets, in order:

const entry: [string, number] = ["Ana", 92];

[string, number] reads “a tuple of a string then a number.” It is still an array when the program runs; the tuple type is extra knowledge the checker keeps about it.

Worked example: A name and a score

tuple-pair.ts
const entry: [string, number] = ["Ana", 92];
console.log(entry[0]);
console.log(entry[1] + 5);
console.log(entry);
console.log(entry.length);
Ana
97
[ 'Ana', 92 ]
2

Line 2 reads index 0, and the checker knows it is a string. Line 3 reads index 1, and the checker knows it is a number, so + 5 adds. Node prints the tuple like any array, and its length is 2, which the checker also knows: hover over entry.length and VS Code shows the type 2.

Because the checker knows every position, it catches three mistakes an array type would miss. Values in the wrong order:

tuple-wrong.ts
const entry: [string, number] = [92, "Ana"];
console.log(entry);
tuple-wrong.ts:1:34 - error TS2322: Type 'number' is not assignable to type 'string'.
tuple-wrong.ts:1:38 - error TS2322: Type 'string' is not assignable to type 'number'.

Too many values:

tuple-too-long.ts
const entry: [string, number] = ["Ana", 92, true];
console.log(entry);
tuple-too-long.ts:1:7 - error TS2322: Type '[string, number, boolean]' is not assignable to type '[string, number]'.
  Source has 3 element(s) but target allows only 2.

And an index that does not exist, which for a plain array would silently give undefined:

tuple-index.ts
const entry: [string, number] = ["Ana", 92];
console.log(entry[2]);
tuple-index.ts:2:19 - error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'.

Fix or delete all three files before your next check. The choice between an array and a tuple comes down to one question: does every position mean the same kind of thing? A list of scores is number[]: any length, every element a score. One result is [string, number]: always two, the name then the score.

Where tuples shine is in an array of them. The type [string, number][] reads “an array of name-and-score tuples”: the outer [] says array, the inner brackets say what each element looks like.

score-table.ts
const results: [string, number][] = [
  ["Ana", 88],
  ["Ben", 95],
  ["Cleo", 91],
];
console.log(results[1]);
console.log(results[1][0]);
console.log(results.length);
results.push(["Dan", 79]);
for (const result of results) {
  console.log(`${result[0].padEnd(6)}${result[1]}`);
}
[ 'Ben', 95 ]
Ben
3
Ana   88
Ben   95
Cleo  91
Dan   79

results[1] is the whole second tuple, and results[1][0] indexes into it: the second result’s name. Line 9 pushes a new tuple, and the checker checks its shape against [string, number]. Lines 10 to 12 loop over the tuples, and inside the loop result[0] is known to be a string (so padEnd, the right-hand twin of Day 3’s padStart, is allowed) and result[1] a number.

Key idea

A tuple type, [string, number], is an array type with a fixed length and a type for each position. The checker rejects a wrong order, a wrong length, and an index that does not exist. [string, number][] is an array of such pairs. Always annotate a tuple; inference gives a plain array instead.

Pause and try

Question 12 · Tracing

Predict exactly what this program shows.

predict-tuple.ts
const item: [string, number, boolean] = ["Lamp", 24.5, true];
console.log(item[0].toUpperCase());
console.log(item[1] * 2);
console.log(item[2] ? "in stock" : "sold out");
console.log(item.length);
Check your reasoning
LAMP
49
in stock
3

The tuple has three positions with three types. item[0] is a string, so toUpperCase is allowed: LAMP. item[1] is a number: 24.5 × 2 is 49. item[2] is a boolean, and the conditional operator picks in stock. The length is 3.

Reread 6.9 Tuples if any line differed.

Question 13 · Multiple choice

Which type fits a list of cities, each a name and a population, such as Lima with 10 million and Oslo with 700 thousand?

  1. [string, number]
  2. [string, number][]
  3. string[]
  4. (string | number)[]
Check your reasoning

B. Each city is a name-then-population tuple, [string, number], and a list of them is an array of tuples.

  • A is wrong: it describes one city, not a list of them.
  • C is wrong: the populations are numbers, not strings.
  • D is wrong: it allows any length and any mix, so the checker could not tell a name from a population.

Reread 6.9 Tuples if you chose differently.

Section 10 of 10

6.10 Destructuring and entries

Reading result[0] and result[1] works, but it is hard to read back: a month later, which one was the score? It would be clearer to give each position a name as soon as the tuple arrives.

Array destructuring does exactly that. On the left of =, write a pattern of names in square brackets; the value on the right is taken apart, and each position goes into the matching name:

const [name, score] = entry;

This is the same as const name = entry[0]; followed by const score = entry[1];, in one line. The pattern can leave a position out with an empty slot, and ...rest at the end collects every remaining element into a new array:

Worked example: Naming the positions

destructure.ts
const entry: [string, number] = ["Ana", 92];
const [name, score] = entry;
console.log(`${name} scored ${score}`);
const colors = ["red", "green", "blue"];
const [first, , third] = colors;
console.log(first, third);
const [head, ...rest] = colors;
console.log(head, rest);
Ana scored 92
red blue
red [ 'green', 'blue' ]
Line Pattern Names and values
2 [name, score] name is "Ana", score is 92
6 [first, , third] first is "red", index 1 skipped, third is "blue"
8 [head, ...rest] head is "red", rest is a new array [ 'green', 'blue' ]

Line 2 takes a tuple apart, and the checker gives name the type string and score the type number, from the tuple’s positions. Lines 6 and 8 take apart a plain string[]; each name gets the element type, string, and rest is a string[]. The pattern on line 6 has two commas in a row: the empty slot between them skips "green".

Destructuring also works in an assignment to existing let variables, and that gives a neat way to swap two values without a temporary variable:

swap.ts
let low = 9;
let high = 2;
if (low > high) {
  [low, high] = [high, low];
}
console.log(low, high);
2 9

Line 4 first builds the array [high, low], which is [2, 9], and then takes it apart into low and high. Without destructuring, swapping needs three lines and a spare variable.

The checker knows a tuple’s length, so a pattern that asks for too many positions is caught:

destructure-short.ts
const point: [number, number] = [3, 4];
const [x, y, z] = point;
console.log(x, y, z);
destructure-short.ts:2:14 - error TS2493: Tuple type '[number, number]' of length '2' has no element at index '2'.

This is the same TS2493 as in 6.9, for the same reason: a [number, number] has no index 2. (A pattern longer than a plain array, const [a, b, c] = [1, 2]; with no annotation, is not caught in the same way, and c would be undefined.) Fix or delete the file.

Now the payoff for 6.7. items.entries() is a method that gives a sequence of [index, element] pairs, one per element, which for...of can walk through. Each pair is a tuple, and destructuring it in the loop header names both parts at once:

entries.ts
const tasks = ["Buy milk", "Walk the dog", "Read"];
for (const [index, task] of tasks.entries()) {
  console.log(`${index + 1}. ${task}`);
}
1. Buy milk
2. Walk the dog
3. Read

This is numbered-list.ts from 6.7 again, with the counting loop gone. On each pass, index is the number and task the element, both with the right types. Use entries() whenever a for...of body needs to know where it is, such as to remember the position of the best element:

find-position.ts
const temps = [18, 21, 25, 22];
let hottestDay = 0;
for (const [day, temp] of temps.entries()) {
  if (temp > temps[hottestDay]) {
    hottestDay = day;
  }
}
console.log(`Day ${hottestDay + 1} was hottest: ${temps[hottestDay]} degrees`);
Day 3 was hottest: 25 degrees

The loop keeps the index of the hottest day in hottestDay, not the temperature, so after the loop both the day and its temperature are available. 25 is at index 2, and hottestDay + 1 turns it into day 3.

Key idea

const [name, score] = entry; names the positions of an array or tuple; an empty slot skips one and ...rest collects the rest. for (const [index, item] of items.entries()) gives the index and the element together.

Pause and try

Question 14 · Tracing

Predict exactly what this program shows. Notice that the loop pattern has a pattern inside it.

predict-destructure.ts
const pairs: [string, number][] = [
  ["tea", 3],
  ["cake", 4],
  ["soup", 6],
];
let total = 0;
for (const [i, [item, price]] of pairs.entries()) {
  total += price;
  console.log(`${i}: ${item} costs ${price}`);
}
const [, cheapest] = pairs[0];
console.log(total, cheapest);
Check your reasoning
0: tea costs 3
1: cake costs 4
2: soup costs 6
13 3

pairs.entries() gives [index, pair] tuples, and each pair is itself a [string, number] tuple, so the pattern [i, [item, price]] names all three parts at once. The loop adds the prices: 3 + 4 + 6 is 13. On line 11, the pattern [, cheapest] skips the name and takes the price of the first pair, 3.

Reread 6.10 Destructuring and entries if any line differed.

Wrap-up · 1 of 8

Putting it together

A small library keeps a catalog that never changes, a list of loans as [title, daysLeft] tuples, and a list of requests. For each request it answers “not in the catalog,” “on loan,” or “checked out,” and then lists what is left on the shelf. Before you type it, make sure npx tsc is clean in your day06 folder: fix or delete any broken file from today.

library.ts
const catalog: readonly string[] = ["Dune", "Emma", "Ulysses", "Beloved"];
const loans: [string, number][] = [
  ["Emma", 3],
  ["Beloved", 10],
];
const requests = ["Dune", "Emma", "Dracula"];

for (const title of requests) {
  if (!catalog.includes(title)) {
    console.log(`${title}: not in the catalog`);
    continue;
  }
  let daysLeft = 0;
  for (const [loaned, days] of loans) {
    if (loaned === title) {
      daysLeft = days;
    }
  }
  if (daysLeft > 0) {
    console.log(`${title}: on loan, back in ${daysLeft} days`);
  } else {
    loans.push([title, 14]);
    console.log(`${title}: checked out for 14 days`);
  }
}

const shelf = [...catalog];
for (const [title] of loans) {
  const position = shelf.indexOf(title);
  if (position !== -1) {
    shelf.splice(position, 1);
  }
}
console.log("On the shelf:");
for (const [index, title] of shelf.entries()) {
  console.log(`${index + 1}. ${title}`);
}
console.log(`Loans: ${loans.length}`);

npx tsc reports no errors, and node library.ts shows:

Dune: checked out for 14 days
Emma: on loan, back in 3 days
Dracula: not in the catalog
On the shelf:
1. Ulysses
Loans: 3
Lines What happens Idea
1 The catalog is readonly: nothing below may change it 6.8
2–5 Loans are an array of tuples, annotated so each pair’s shape is checked 6.9
9–12 A title missing from the catalog is reported, and continue skips the rest 6.6, Day 5
13–18 An inner for...of takes each loan apart; a matching title sets daysLeft 6.10, 6.7
19–24 On loan or not; a new loan is pushed as a fresh [title, 14] tuple 6.3, 6.9
27 A changeable copy of the read-only catalog 6.5, 6.8
28–33 For each loaned title, find its index and splice it out of the copy 6.6, 6.4
35–37 entries() numbers the remaining titles 6.10

Follow "Dune" through: it is in the catalog, no loan matches it, so daysLeft stays 0, and line 22 pushes ["Dune", 14]. "Emma" is in the catalog and matches the first loan, so daysLeft becomes 3. "Dracula" fails the includes check on line 9. At line 27, loans has three tuples; the pattern [title] on line 28 takes only the first position of each. Three titles are spliced out of the four-element copy, and one remains. The catalog itself still has four titles, as readonly promised.

Wrap-up · 2 of 8

Common mistakes

Today’s messages and silent surprises in one place. The first group comes from npx tsc; the second shows no message at all.

Message or symptom Usual cause Fix
TS2322: Type 'string' is not assignable to type 'number'. An element of the wrong type, or tuple values in the wrong order Fix the element; check the tuple’s positions
TS2322: ... Source has 3 element(s) but target allows only 2. Too many values for a tuple type Match the tuple’s length
TS2365: Operator '+' cannot be applied to types 'string | number' ... A mixed literal inferred as (string | number)[] Annotate the array or the tuple
TS2345: Argument of type 'string' is not assignable to parameter ... includes or indexOf with a value of another type Search for the element type
TS2339: Property 'push' does not exist on type 'readonly string[]'. Changing a read-only array Copy it with [...items] first
TS2542: Index signature in type 'readonly string[]' only permits reading. Assigning to an index of a read-only array Copy it first
TS4104: The type 'readonly string[]' is 'readonly' and cannot be assigned ... Giving a read-only array a mutable type Copy it instead
TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'. Indexing or destructuring past a tuple’s end Use an index that exists
TS2588: Cannot assign to 'list' because it is a constant. Replacing a const array with = Change the array, or declare it with let
TS2839: This condition will always return 'false' ... === between two array literals Compare the contents, such as with join
TypeError: Cannot read properties of undefined (from node) Indexing past the end with square brackets The last index is length - 1
A second variable changes too const alias = original; shares one array slice() or [...original]
push “gave back” a number push gives the new length, not the array Keep using the array itself
Elements vanish in a loop Removing from the array being looped over Loop over a copy, or build a new array
A splice removed too much No deleteCount, so everything from start went splice(start, 1)
The original order is gone reverse() changes the array in place [...items].reverse()
if (items.indexOf(x)) is backwards -1 is truthy and 0 is falsy includes, or indexOf(x) !== -1
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
array One value that holds several values, its elements, in order [88, 92, 79]
array literal Elements written between square brackets, separated by commas ["eggs", "milk"]
element One value inside an array 92 in [88, 92, 79]
number[] The type “array of numbers”; string[] and boolean[] likewise const scores: number[] = [];
index An element’s position, counted from 0 scores[1] is 92
mutable Can be changed in place; arrays are, strings are not scores[0] = 90;
push, pop Add at the end (gives the new length); remove the last (gives the element) scores.push(70);
unshift, shift Add at the start; remove the first line.shift();
splice Remove and/or insert elements at an index, in place; gives back the removed ones list.splice(2, 1);
reference What a variable holds for an array: a way of pointing at the one array in memory const alias = original;
slice A new array holding part, or all, of another; the original is untouched days.slice(1, 3)
spread operator ...items inside a literal: every element of items, written out here [...a, ...b]
includes, indexOf Is x an element? At which index (or -1)? guests.includes("Ben")
argument A value passed in a method’s parentheses; TS2345 reports one of the wrong type "102" in ids.includes("102")
readonly Marks an array type the checker only lets you read readonly string[]
tuple An array type with a fixed length and a type for each position [string, number]
destructuring A pattern of names that takes an array or tuple apart const [name, score] = entry;
entries() The [index, element] pairs of an array, for a for...of loop for (const [i, x] of items.entries())
Wrap-up · 4 of 8

Summary

  • An array literal [88, 92, 79] holds elements in order; the checker infers number[] or string[], and an empty [] needs an annotation. Indexes start at 0, the last is length - 1, and a position past the end gives undefined with no warning from the checker.
  • Arrays are mutable: items[i] = x, push/pop at the end, unshift/shift at the start, and splice(start, count, ...new) in the middle all change the array in place. A const array can be changed but not replaced.
  • A variable holds a reference, so const alias = original; gives one array two names. Copy with slice() or [...items]; join with [...a, ...b]. === compares references, and reverse() changes the array in place.
  • includes(x) asks yes or no; indexOf(x) gives the first index or -1, which is truthy, so compare it with -1. Both accept only the element type.
  • for...of visits each element; a counting for or entries() gives the index too; accumulate with a let and build new arrays by pushing. Never remove from the array you are looping over.
  • readonly string[] makes the checker reject every change. A tuple [string, number] fixes the length and the type of each position, and destructuring const [name, score] = entry; names the positions.
Wrap-up · 5 of 8

Practice

Do these in your day06 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as wrong-element.ts, mixed-list.ts, const-list-reassign.ts, compare-literals.ts, includes-wrong-type.ts, readonly-push.ts, readonly-assign.ts, readonly-to-mutable.ts, inferred-pair.ts, tuple-wrong.ts, tuple-too-long.ts, tuple-index.ts, or destructure-short.ts), fix it or delete it. Then type each program yourself, check it with npx tsc, run it with node, and only then open the answer. Change the starting values and run them again, including an empty array where it makes sense.

Question 15 · Short answer

Remove duplicates. Store a list of names with repeats in an array, such as the visitors to a shop in the order they arrived. Build a new array that holds each name once, in the order it first appeared, and show it. Do not change the original array.

Check your reasoning

One possible solution:

unique.ts
const visits = ["Ana", "Ben", "Ana", "Cleo", "Ben", "Ana"];
const unique: string[] = [];
for (const name of visits) {
  if (!unique.includes(name)) {
    unique.push(name);
  }
}
console.log(unique);
[ 'Ana', 'Ben', 'Cleo' ]

This is the “loop, test, push” pattern from 6.7, with includes as the test. For each name in the original, the program asks whether unique already has it; only a name seen for the first time is pushed, so each name appears once and the order of first appearance is kept. visits is never changed. Try an empty visits array: the loop runs no passes and unique prints as [].

Reread 6.7 Looping over an Array and 6.6 Searching an Array if your result differed.

Question 16 · Short answer

Rotate left. Store an array of numbers and a count k (it stands for any whole number, so annotate it). Build the array rotated left by k positions: the first k elements move to the end, in the same order. Rotating [1, 2, 3, 4, 5] by 2 gives [3, 4, 5, 1, 2]. Make it work when k is larger than the array’s length, and show the original array afterwards to prove it is unchanged.

Check your reasoning

One possible solution:

rotate.ts
const items = [1, 2, 3, 4, 5];
const k: number = 7;
const shift = k % items.length;
const rotated = [...items.slice(shift), ...items.slice(0, shift)];
console.log(rotated);
console.log(items);
[ 3, 4, 5, 1, 2 ]
[ 1, 2, 3, 4, 5 ]

Rotating by the length brings the array back to where it started, so line 3 reduces k with Day 2’s remainder: 7 % 5 is 2. Then slice(shift) is the part from index 2 on, [3, 4, 5], and slice(0, shift) is the first two, [1, 2]; spreading both into one literal, in that order, builds the rotated array. slice never changes items, so line 6 shows the original. Try k of 0, 5, and 12.

The same job can be done in place, moving one element at a time with shift and push:

rotate-loop.ts
const items = [1, 2, 3, 4, 5];
const k: number = 2;
for (let i = 0; i < k % items.length; i++) {
  items.push(items[0]);
  items.shift();
}
console.log(items);
[ 3, 4, 5, 1, 2 ]

Each pass pushes a copy of the first element onto the end and then shifts the first element off. This version changes items, so it would not meet the “unchanged original” part of the question; it is here to show both tools.

Reread 6.5 Copying an Array and 6.3 Changing an Array if your result differed.

Question 17 · Short answer

Highest scorer. Store test results as an array of [name, score] tuples. Find the student with the highest score and show their name and score in one sentence.

Check your reasoning

One possible solution:

highest-scorer.ts
const results: [string, number][] = [
  ["Ana", 88],
  ["Ben", 95],
  ["Cleo", 91],
];
let [bestName, bestScore] = results[0];
for (const [name, score] of results) {
  if (score > bestScore) {
    bestName = name;
    bestScore = score;
  }
}
console.log(`Highest scorer: ${bestName} with ${bestScore}`);
Highest scorer: Ben with 95

The annotation [string, number][] tells the checker that every element is a name-then-score pair. Line 6 starts the best-so-far at the first result, taking it apart into two let variables so they can be updated. The loop destructures each tuple in its header; whenever a score beats the best so far, both the name and the score are replaced, so they always belong to the same student. Try two students with the same top score: > keeps the first of them, and >= would keep the last.

Reread 6.10 Destructuring and entries and 6.9 Tuples if your result differed.

Wrap-up · 6 of 8

Review questions

Question 18 · Tracing

Predict exactly what this program shows. Write out the array after each line.

review-queue.ts
const orders = ["tea", "cake"];
orders.push("soup", "pie");
orders.shift();
orders.unshift("water");
const gone = orders.splice(2, 1);
console.log(orders);
console.log(gone, orders.length, orders.at(-1));
Check your reasoning
[ 'water', 'cake', 'pie' ]
[ 'soup' ] 3 pie
Line Call orders afterwards
2 push("soup", "pie") [ 'tea', 'cake', 'soup', 'pie' ]
3 shift() [ 'cake', 'soup', 'pie' ]
4 unshift("water") [ 'water', 'cake', 'soup', 'pie' ]
5 splice(2, 1) [ 'water', 'cake', 'pie' ]

splice gives back the removed elements as an array, so gone is [ 'soup' ], with brackets. The length is 3 and at(-1) is the last element.

Reread 6.3 Changing an Array and 6.4 Inserting and Removing with splice if any line differed.

Question 19 · Tracing

Predict exactly what this program shows. Count the arrays first.

review-alias.ts
const stock = ["bolt", "nut", "washer"];
const backup = stock;
const copy = stock.slice(1);
stock.splice(1, 1, "screw");
backup.push("pin");
console.log(stock);
console.log(backup.length, copy);
Check your reasoning
[ 'bolt', 'screw', 'washer', 'pin' ]
4 [ 'nut', 'washer' ]

There are two arrays: stock and backup are two names for the first, and copy is a new array made by slice(1) before anything changed, holding [ 'nut', 'washer' ]. Line 4 replaces index 1 of the shared array with "screw", and line 5 pushes "pin" onto the same array through its other name. So stock shows four elements, backup.length is also 4, and copy still has the two elements it was given.

Reread 6.5 Copying an Array if any line differed.

Question 20 · Debugging

A café’s menu must never change, but today’s special should be offered too. npx tsc rejects this program. Predict the message, explain it, and write the fix.

menu-readonly.ts
const menu: readonly string[] = ["tea", "cake", "soup"];
const special: string = "pie";
if (!menu.includes(special)) {
  menu.push(special);
}
console.log(menu.join(", "));
Check your reasoning
menu-readonly.ts:4:8 - error TS2339: Property 'push' does not exist on type 'readonly string[]'.

menu is a read-only array, so the checker treats it as having no push; column 8 is the word push. The readonly is right, because the menu must not change, so the fix is not to remove it. Copy the menu into an ordinary array and add the special there:

menu-readonly-fixed.ts
const menu: readonly string[] = ["tea", "cake", "soup"];
const special: string = "pie";
const today = [...menu];
if (!today.includes(special)) {
  today.push(special);
}
console.log(today.join(", "));
console.log(menu.length);
tea, cake, soup, pie
3

[...menu] builds a new string[], which may be pushed to, and line 8 shows that menu still has its three items. If you typed the original program, fix or delete it before you go on.

Reread 6.8 readonly Arrays if you missed it.

Question 21 · Tracing

Predict exactly what this program shows.

review-entries.ts
const words = ["sun", "moon", "star"];
const labels: string[] = [];
for (const [i, word] of words.entries()) {
  if (word.length === 4) {
    continue;
  }
  labels.push(`${i}-${word.toUpperCase()}`);
}
console.log(labels.join(" "));
console.log(labels.length);
Check your reasoning
0-SUN
1

entries() gives [0, "sun"], [1, "moon"], and [2, "star"]. Both "moon" and "star" have four characters, so continue skips them, and only "sun" is pushed as "0-SUN". labels then has one element, and joining one element with " " gives just that element.

Reread 6.10 Destructuring and entries and 6.7 Looping over an Array if any line differed.

Question 22 · Multiple choice

const ids = [4, 8, 15]; has been declared, and wanted is a number. Which condition is true exactly when wanted is one of the ids?

  1. ids.indexOf(wanted)
  2. ids.includes(wanted)
  3. ids.indexOf(wanted) > 0
  4. ids.includes(wanted) === -1
Check your reasoning

B. includes is the yes-or-no question, and it is true for every element, including the first.

  • A is wrong: indexOf gives -1 for “not found,” which is truthy, and 0 for the first element, which is falsy; the condition is backwards.
  • C is wrong: > 0 leaves out index 0, so wanted of 4 would count as missing. It should be !== -1.
  • D is wrong: includes gives a boolean, which can never equal -1; the checker rejects the comparison with TS2367.

Reread 6.6 Searching an Array if you chose differently.

Question 23 · Short answer

A program stores a book as ["Dune", 412] and a reading list of titles as ["Dune", "Emma"]. Which of the two should be typed as a tuple and which as an array, and what would the checker stop catching if you swapped the choices?

Check your reasoning

Model answer: The book is a tuple, [string, number]: it always has exactly two positions, and position 0 (the title) means something different from position 1 (the page count). The reading list is an array, string[]: any number of titles, every element the same kind of thing. Typed as a plain array, the book would be inferred as (string | number)[], so the checker could no longer tell that index 1 is a number (no arithmetic on the page count), would allow a third element, and would let book[5] through. Typed as a tuple such as [string, string], the reading list would be stuck at exactly two titles: the checker would reject a list of three.

A complete answer must:

  • say the book is a tuple because it has a fixed number of positions with different meanings or types,
  • say the reading list is an array because it has any number of elements of one type, and
  • name at least one check that is lost with the wrong choice (element type at a position, length, or an index past the end).

Reread 6.9 Tuples if your reasoning differed.

Question 24 · Multiple choice

const scores = [70, 85]; has been declared. Which expression has the type number | undefined according to the checker?

  1. scores[1]
  2. scores[5]
  3. scores.at(-1)
  4. scores.length
Check your reasoning

C. The checker knows at can run off the end, so it gives its result the type number | undefined, just as it did for strings on Day 3.

  • A and B are wrong: square brackets are typed as plain number for every index, even index 5, which gives undefined when run. The checker does not track which indexes exist.
  • D is wrong: length is always a number.

Reread 6.2 Indexing and Length if you chose differently.

Wrap-up · 7 of 8

Go further

The Handbook’s pages explain array and tuple types in the checker’s own terms, and MDN’s guide tours every array method: TypeScript Handbook: Everyday Types (the “Arrays” section), TypeScript Handbook: Object Types (the “Tuple Types” section), and MDN: Indexed collections.

Wrap-up · 8 of 8

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can write an array literal, say whether its type is number[] or string[], and annotate an empty one. Reread
  • I can read an element by index or with at(-1), and explain what an index past the end gives. Reread
  • I can change an array with index assignment, push, pop, shift, and unshift, and say what each gives back. Reread
  • I can remove or insert elements in the middle of an array with splice. Reread
  • I can explain why two names for one array see the same changes, and copy an array with slice or spread. Reread
  • I can search an array with includes and indexOf, and compare indexOf with -1. Reread
  • I can loop over an array with for...of, accumulate a total or maximum, and build a new array by pushing. Reread
  • I can mark an array readonly and explain which lines the checker then rejects. Reread
  • I can describe a fixed-shape value with a tuple type and choose between a tuple and an array. Reread
  • I can take a tuple apart with destructuring and loop with entries() to get the index and element. Reread