An array is an ordered list stored in a single variable: a playlist, a to-do list, the scores in a game or the products in a basket. Instead of separate variables called song1, song2 and song3, you have one songs array that can hold as many songs as you need.
Arrays are one of the two main ways JavaScript groups data (the other is objects). Most data a website works with, from search results to chat messages, arrives as an array. Learning to create, read and change them is the foundation for the array methods in the next lesson.
Creating an array and reading items
const pets = ["cat", "dog", "hamster"];- Items are separated by commas inside square brackets.
- Each item has an index, starting at 0, so
pets[0]is"cat". pets.lengthis the number of items (3). The last item ispets[pets.length - 1]orpets.at(-1).- Arrays can hold any type of value, even a mix:
[1, "two", true, { id: 4 }]. - Change an item by its index:
pets[1] = "parrot".
Reading an index that doesn't exist, such as pets[10], doesn't cause an error. It returns undefined, which can hide mistakes, so check length when in doubt.
Adding and removing items
| Method | What it does | Changes the array? |
|---|---|---|
push(x) | Adds to the end | Yes |
pop() | Removes from the end and returns it | Yes |
unshift(x) | Adds to the start | Yes |
shift() | Removes from the start and returns it | Yes |
splice(i, n) | Removes n items at index i (and can insert) | Yes |
slice(a, b) | Copies a section | No |
concat() / [...a, ...b] | Combines arrays | No |
The last column matters. Methods that change the original array affect every part of your code that uses it, while copying methods leave the original untouched.
Searching an array
includes(x)returnstrueorfalse.indexOf(x)returns the item's index, or-1if it isn't there.join(", ")turns the array into a single string.- To search with a condition, such as "the first price over 10", use
findfrom Array Methods.
Looping through an array
To do something with every item, use a for...of loop:
for (const pet of pets) {
console.log(`I have a ${pet}`);
}If you also need each item's position, use a classic for loop with an index from 0 up to, but not including, pets.length. See for Loops.
JavaScript Arrays Syntax
Array basics
const list = ["a", "b", "c"];
list[0]; // "a"
list.length; // 3
list.push("d"); // add to end
list.pop(); // remove from end
list.includes("b"); // trueJavaScript Arrays Summary
- An array stores an ordered list of values in one variable.
- Indexes start at 0, and
lengthgives the number of items. push,pop,shift,unshiftandsplicechange the array;sliceand spread make copies.includesandindexOfsearch for a value.- Use
for...ofto visit every item.
JavaScript Arrays Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Reading and changing items
const planets = ["Mercury", "Venus", "Earth", "Mars"];
console.log(planets[0]);
console.log(planets[2]);
console.log(planets.length);
console.log(planets.at(-1));
planets[3] = "Mars 🔴";
console.log(planets);
console.log(planets[10]);Line-by-line explanation
- Lines 3 to 4Index 0 is the first item; index 2 is the third.
- Line 5Four items.
- Line 6
at(-1)counts from the end. - Line 8Replace an item by assigning to its index.
- Line 10Reading past the end gives
undefined, not an error.
A to-do list
const todos = ["Buy milk", "Walk dog"];
todos.push("Learn arrays");
todos.unshift("Wake up");
console.log(todos);
const done = todos.shift();
console.log("Done:", done);
const index = todos.indexOf("Walk dog");
todos.splice(index, 1);
console.log(todos);
console.log(`${todos.length} left: ${todos.join(", ")}`);Line-by-line explanation
- Line 3Add to the end.
- Line 4Add to the start.
- Line 7Remove (and get back) the first item.
- Lines 10 to 11Find an item's position, then remove 1 item there.
- Line 13
jointurns the array into a readable string.
Nested arrays and copies
const board = [
["X", "O", "X"],
["", "X", "O"],
["O", "", "X"],
];
console.log("Centre square:", board[1][1]);
const original = [1, 2, 3];
const copy = original.slice();
copy.push(4);
console.log(original, copy);
const combined = [...original, ...[10, 20]];
console.log(combined);Line-by-line explanation
- Lines 1 to 5An array of arrays, forming a noughts and crosses board.
- Line 6First pick the row, then the column.
- Line 9
slice()with no arguments makes a copy, so changing it doesn't affect the original. - Line 13Spread
...combines arrays into a new one.
Common JavaScript Arrays Mistakes
Index starts at 1
const colors = ["red", "green", "blue"];
console.log(colors[1]); // "green", not "red"console.log(colors[0]); // "red"Copying by assignment
const a = [1, 2];
const b = a; // same array, two names!
b.push(3);
console.log(a); // [1, 2, 3]const a = [1, 2];
const b = [...a]; // a real copy
b.push(3);
console.log(a); // [1, 2]Arrays are stored by reference. b = a doesn't copy; it gives the same array another name.
Using === to compare arrays
[1, 2] === [1, 2]; // falseJSON.stringify([1, 2]) === JSON.stringify([1, 2]); // true (simple arrays)=== checks whether two arrays are the same object, not whether they have the same contents.
JavaScript Arrays in Real Projects
Arrays are everywhere
Search results, chat messages, notifications, products, comments and photo galleries all arrive as arrays, usually arrays of objects like [{ id: 1, title: "…" }, …]. Much of front-end code is about turning arrays of data into lists on the screen.
JavaScript Arrays Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Add "kiwi" to the end and remove the first item.
const fruit = ["apple", "pear"];
fruit.("kiwi");
fruit.();
console.log(fruit); // ["pear", "kiwi"]
push adds to the end; shift removes from the start.What does this print?
const nums = [5, 10, 15];
console.log(nums.length, nums[nums.length - 1]);What does this print?
const a = ["x"];
const b = a;
b.push("y");
console.log(a.length);b and a are the same array.The code should remove "Tuesday" from the list and log Mon, Wed, Thu. Fix it.
const days = ["Mon", "Tue", "Wed", "Thu"];
const pos = days.indexOf("Tuesday");
days.splice(pos);
console.log(days.join(", "));- Logs "Mon, Wed, Thu"
splice needs to know how many items to remove.JavaScript Arrays Quiz
4 questions to check what you learned.
What is the index of the first item in an array?
- 0
- 1
- -1
- It depends
Which method removes the last item and returns it?
- shift()
- slice()
- remove()
- pop()
What does
["a", "b"].indexOf("z")return?- 0
- null
- -1
- false
Which method copies part of an array without changing the original?
- splice
- pop
- shift
- slice
JavaScript Arrays Challenge
Manage a playlist
Starting from the playlist:
- Add
"Dancing Queen"to the end - Add
"Bohemian Rhapsody"to the start - Remove
"Yellow"usingindexOf+splice - Log
4 songs: Bohemian Rhapsody, Hey Jude, Imagine, Dancing Queen
const playlist = ["Hey Jude", "Yellow", "Imagine"];
- Playlist is in the right order
- Logs the summary