Arrays: creating, reading and changing lists
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
What an array is
An array is an ordered list of values. You use it whenever you have many things of the same kind: a list of products, usernames, prices or tasks. You write an array with square brackets and commas.
const fruits = ["mango", "apple", "banana"];
const mixed = [1, "two", true, null];
const empty = [];
An array can hold any type, even other arrays. In practice, keep one kind of thing in one array. It makes the code easier to work with.
Reading and changing items
Each item has a position, called an index, starting at 0.
const fruits = ["mango", "apple", "banana"];
console.log(fruits[0]); // "mango"
console.log(fruits[2]); // "banana"
console.log(fruits[5]); // undefined, there is no item 5
console.log(fruits.length); // 3
console.log(fruits.at(-1)); // "banana", last item
fruits[1] = "orange"; // replace an item
console.log(fruits); // ["mango", "orange", "banana"]
The last item is always at length - 1. Reading a position that does not exist does not crash, it just gives undefined.
Remember the lesson on const. You can still change items of a const array. You only cannot assign a whole new array to the same name.
Adding and removing items
| Method | What it does | Returns |
|---|---|---|
push(x) | Adds to the end | New length |
pop() | Removes from the end | The removed item |
unshift(x) | Adds to the start | New length |
shift() | Removes from the start | The removed item |
splice(i, n, ...items) | Removes n items at i, optionally inserts new ones | Array of removed items |
const queue = ["Ali", "Sara"];
queue.push("Omar"); // ["Ali", "Sara", "Omar"]
queue.unshift("Zain"); // ["Zain", "Ali", "Sara", "Omar"]
const last = queue.pop(); // "Omar"
const first = queue.shift(); // "Zain"
console.log(queue, last, first); // ["Ali", "Sara"] "Omar" "Zain"
const letters = ["a", "b", "c", "d"];
letters.splice(1, 2); // remove "b" and "c"
console.log(letters); // ["a", "d"]
letters.splice(1, 0, "x", "y"); // insert at position 1, remove nothing
console.log(letters); // ["a", "x", "y", "d"]
These methods change the original array. That is called mutation. It is fine when you mean it, and a source of bugs when you do not. If you pass an array to a function and that function calls push, the caller's array changes too.
Finding things
const numbers = [10, 20, 30, 20];
console.log(numbers.includes(30)); // true
console.log(numbers.indexOf(20)); // 1
console.log(numbers.lastIndexOf(20)); // 3
console.log(numbers.indexOf(99)); // -1, not found
Slicing, joining and copying
slice takes a part of an array without changing the original. It works like the string version: the end position is not included.
const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
console.log(days.slice(1, 3)); // ["Tue", "Wed"]
console.log(days.slice(-2)); // ["Thu", "Fri"]
console.log(days.join(" | ")); // "Mon | Tue | Wed | Thu | Fri"
To make a copy, use the spread syntax [...array]:
const original = [1, 2, 3];
const copy = [...original];
const extended = [...original, 4, 5];
copy.push(99);
console.log(original); // [1, 2, 3], untouched
console.log(copy); // [1, 2, 3, 99]
console.log(extended); // [1, 2, 3, 4, 5]
Just writing const copy = original does not make a copy. It gives the same array a second name. Changes through one name show up through the other. This is the single most common array bug I see in beginner code.
Sorting and reversing
const nums = [10, 9, 1, 100];
nums.sort();
console.log(nums); // [1, 10, 100, 9] surprising!
By default sort turns items into strings and compares them as text, so "100" comes before "9". For numbers, pass a compare function:
nums.sort((a, b) => a - b);
console.log(nums); // [1, 9, 10, 100]
If a - b is negative, a goes first. sort and reverse also mutate the array. To keep the original, copy first: [...nums].sort((a, b) => a - b).
Arrays of arrays
Arrays can contain arrays, which is a simple way to model a grid:
const grid = [
[1, 2, 3],
[4, 5, 6],
];
console.log(grid[1][2]); // 6, second row, third column
Common mistakes
- **Thinking
const copy = originalcopies.** Use[...original]. - Sorting numbers without a compare function. You get text order.
- Off-by-one errors. The last index is
length - 1. - Forgetting that push/pop/splice/sort mutate. Copy first if you need the original.
- **Using
delete array[1].** It leaves an empty hole. Usesplice.
Try it yourself
- Create an array of five cities. Add one to the end, remove the first, and print the result.
- Given
[5, 3, 8, 1], print the numbers sorted from smallest to largest without changing the original array. - Make a copy of
["a", "b", "c"], add "d" to the copy, and show that the original did not change. - Remove the item at position 2 from
[1, 2, 3, 4, 5]usingsplice.
const fruits = ["mango", "apple", "banana"];
console.log(fruits[0]); // "mango"
console.log(fruits[2]); // "banana"
console.log(fruits[5]); // undefined, there is no item 5
console.log(fruits.length); // 3
console.log(fruits.at(-1)); // "banana", last item
fruits[1] = "orange"; // replace an item
console.log(fruits); // ["mango", "orange", "banana"]
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account