Bitpath

Lesson 1 · Unit 04

Arrays

Lists with positions from 0: reading, adding, removing, copying and sharing

13 exercisesabout 3 min

What you practise

  • Indexes from 0, length, push, pop, shift, includes, indexOf, slice against splice, an array can change and two names can share it

Try a question from this lesson

Pick one

An array holds several values in order, between square brackets. Positions work as they do in a string. What do you think this prints?

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

In a string, which position does the first character have?

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 a list of values in square brackets, separated by commas.

Each item has an index, starting at 0. length is the number of items, so the last index is length - 1.

Assigning to an index replaces that item. Printing a whole array shows it in brackets.

JavaScript
const fruit = ["apple", "kiwi", "plum"];
console.log(fruit[0]);     // apple
console.log(fruit.length); // 3
fruit[1] = "pear";
console.log(fruit);
// [ 'apple', 'pear', 'plum' ]

Concept

Adding, removing, finding

push(x) adds x at the end. pop() removes and returns the last item. shift() removes and returns the first.

includes(x) is true when x is in the array.

indexOf(x) gives the index of x, or -1 when it is not there. You met it on strings.

JavaScript
const queue = ["Ana", "Bo"];
queue.push("Cy");            // Ana Bo Cy
const first = queue.shift(); // Bo Cy
console.log(first);                // Ana
console.log(queue.includes("Bo")); // true
console.log(queue.indexOf("Cy"));  // 1

Concept

Two names, one array

A variable does not contain an array. It refers to one.

const b = a makes no copy: both names now refer to the same array, and a change made through one is seen through the other. a.slice() makes a real copy.

const only stops the name being given another value. The array itself can still change.

JavaScript
const a = [1, 2];
const b = a;         // same array
const c = a.slice(); // a copy
b.push(3);
console.log(a.length); // 3
console.log(c.length); // 2

9 more exercises in the app

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

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