Lesson 1 · Unit 04
Arrays
Lists with positions from 0: reading, adding, removing, copying and sharing
What you practise
- Indexes from 0,
length,push,pop,shift,includes,indexOf,sliceagainstsplice, 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?
const scores = [70, 85, 90];
console.log(scores[1]);Hint
In a string, which position does the first character have?
Correct answer
85
Why
Positions start at 0, exactly as in a string, so scores[1] is the second item. The position of an item is called its index. scores[0] is 70.
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.
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.
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")); // 1Concept
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.
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); // 29 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.