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.
| Method | What it does | Gives back |
|---|---|---|
push(x) | adds x at the end | the new length |
pop() | removes the last item | that item |
unshift(x) | adds x at the start | the new length |
shift() | removes the first item | that item |
splice(i, n) | removes n items from index i | the removed items |
slice(a, b) | does not change the array | a copy of items a up to (not including) b |
includes(x), indexOf(x) | does not change the array | true 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);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);Line by line
liststarts with two items.pushadds"milk"at the end, andunshiftadds"tea"at the start.- The first
console.logshows all four items, and the length. popremoves the last item and gives it back, solastis"milk".includesfinds"eggs", andindexOfsays that"rice"is at position 1, because"tea"is now first.slice(0, 2)makes a new list of the first two items, andliststays 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 isundefined, not an error, so the mistake can hide. - Expecting
b = ato 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
sliceandsplice.slicecopies, andspliceremoves items from the array.
Best practices
- Use
constfor 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
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.