Arrays

Introduction

Programs rarely deal with one value at a time. They deal with all the marks in a class or every item in a cart. An array is an ordered list of values, written in square brackets, and it lets one variable stand for many values. Because the list has an order, each item has a position, which is called its index.

How it works

const marks = [72, 85, 64];
marks[0]        // 72, the first item
marks.length    // 3
marks[marks.length - 1]   // 64, the last item

Indexes count from 0 because an index really says how far an item is from the start.

Changing an array.

MethodWhat it doesGives back
push(x)adds x at the endthe new length
pop()removes the last itemthat item
unshift(x)adds x at the startthe new length
shift()removes the first itemthat item
splice(i, n)removes n items from index ithe removed items
slice(a, b)does not change the arraya copy of items a up to (not including) b
includes(x), indexOf(x)does not change the arraytrue or false, the index or -1

The visualizer draws the array in the heap, the part of memory where objects live, with an arrow from the variable to it.

Two names, one array. An array is an object. A variable does not hold the array itself, only a reference (an arrow) to it. Copying the variable copies the arrow, so both names point at the same array:

// Copying a variable copies the reference, not the array.
const a = [1, 2, 3];
const b = a;            // b points at the same array
b.push(4);
console.log(a);         // a sees the change too
const c = [...a];       // a real copy
c.push(5);
console.log(a, c);
console.log(a === b, a === c);
Open in compiler

const stops the variable from pointing somewhere else, but the array it points at can still change. To get a real copy, use [...list] (the spread syntax) or list.slice().

Syntax

const list = ["a", "b"];
list.push("c");
const last = list.pop();
const copy = [...list];
for (let i = 0; i < list.length; i++) { console.log(i, list[i]); }

Example

// Build and change a shopping list.
const list = ["rice", "eggs"];
list.push("milk");               // add at the end
list.unshift("tea");             // add at the start
console.log(list, list.length);
const last = list.pop();         // remove the last item
console.log("Bought", last, "- still need", list);
console.log(list.includes("eggs"), list.indexOf("rice"));
const firstTwo = list.slice(0, 2);
console.log(firstTwo);
Open in compiler

Line by line

  1. list starts with two items.
  2. push adds "milk" at the end, and unshift adds "tea" at the start.
  3. The first console.log shows all four items, and the length.
  4. pop removes the last item and gives it back, so last is "milk".
  5. includes finds "eggs", and indexOf says that "rice" is at position 1, because "tea" is now first.
  6. slice(0, 2) makes a new list of the first two items, and list stays as it was.

Expected result

[ 'tea', 'rice', 'eggs', 'milk' ] 4
Bought milk - still need [ 'tea', 'rice', 'eggs' ]
true 1
[ 'tea', 'rice' ]

In the real world

A feed of posts, the rows of a table and the results of a search are all arrays. The sharing rule causes real bugs: a function that changes a list it was given also changes the caller's list. That is why careful code copies a list before changing it.

Common mistakes

  • Reading past the end. marks[3] in a 3-item array is undefined, not an error, so the mistake can hide.
  • Expecting b = a to copy an array. Both names share one array.
  • Comparing arrays with ===. It checks whether they are the same array, not whether the items match.
  • Mixing up slice and splice. slice copies, and splice removes items from the array.

Best practices

  • Use const for arrays, because you will rarely need to point the name at another array.
  • Copy a list before changing it if someone else may still be using it.
  • Keep the items of one array of the same kind, so that code can treat them all alike.

Summary

Arrays are ordered lists with indexes from 0. push, pop, shift, unshift and splice change them, and slice copies part of one. A variable holds a reference, so copying a variable shares the array, and [...list] makes a real copy.

Quick check

1. const a = [5, 8, 2]. What is a[1]?
2. const a = [1, 2]; const b = a; b.push(3); what is a?
3. Which method removes and returns the last item?
4. What is [1, 2] === [1, 2]?

Key takeaways

  • Indexes start at 0, so the last item is at length - 1.
  • Copying a variable copies the reference, not the array.
  • slice copies and splice changes the array.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.