Bitpath

Lesson 1 · Unit 04

Arrays and tuples

Ordered lists, numbered from 0, with a type for their items

13 exercisesabout 3 min

What you practise

  • number[], indexes from 0, length, push, pop, includes, slice, tuples, readonly, an array can change and two names can share it

Try a question from this lesson

Pick one

Square brackets hold a list of values. Its items are numbered like the characters of a string. What do you think this prints?

TypeScript
const scores = [70, 85, 90];
console.log(scores[1]);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Arrays

An array is an ordered list of values under one name. The values are its items, and each has a position, its index, starting at 0.

The type number[] reads "array of numbers". All items of an array have the same type.

.length is the number of items. The last item is at index length - 1. You can replace an item by storing into its index.

TypeScript
const scores: number[] = [70, 85, 90];
console.log(scores[0]);     // 70
console.log(scores.length); // 3
scores[0] = 75;             // replace
console.log(scores[0]);     // 75

Concept

includes and slice

includes(x) answers with a boolean: is x one of the items?

slice(from, to) makes a new array with a copy of the items from index from up to, but not including, index to. Leave out to and it runs to the end.

The original array is not changed by either.

TypeScript
const days = ["Mon", "Tue", "Wed", "Thu"];
console.log(days.includes("Wed")); // true
const mid = days.slice(1, 3);
console.log(mid.length);  // 2: Tue, Wed
console.log(days.length); // 4, untouched

Concept

Tuples and readonly

A tuple is an array with a fixed number of items and a type for each position. [string, number] means exactly one string, then one number.

Put readonly in front of an array type and the compiler rejects every attempt to change the array: no storing into an index, no push.

Both are promises that the compiler keeps for you.

TypeScript
const point: [number, number] = [3, 4];
const who: [string, number] = ["Ada", 36];
const days: readonly string[] = ["Mon"];
console.log(point[0] + point[1]); // 7
console.log(who[0], days[0]); // Ada Mon

9 more exercises in the app

  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy