JavaScript Arrays

Ordered lists of values: create, read, add, remove and search.

Lesson 23 of 56Beginner13 min read

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

JavaScript
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.length is the number of items (3). The last item is pets[pets.length - 1] or pets.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

MethodWhat it doesChanges the array?
push(x)Adds to the endYes
pop()Removes from the end and returns itYes
unshift(x)Adds to the startYes
shift()Removes from the start and returns itYes
splice(i, n)Removes n items at index i (and can insert)Yes
slice(a, b)Copies a sectionNo
concat() / [...a, ...b]Combines arraysNo

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) returns true or false.
  • indexOf(x) returns the item's index, or -1 if 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 find from Array Methods.

Looping through an array

To do something with every item, use a for...of loop:

JavaScript
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"); // true

JavaScript Arrays Summary

  • An array stores an ordered list of values in one variable.
  • Indexes start at 0, and length gives the number of items.
  • push, pop, shift, unshift and splice change the array; slice and spread make copies.
  • includes and indexOf search for a value.
  • Use for...of to visit every item.

JavaScript Arrays Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

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]);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 3 to 4Index 0 is the first item; index 2 is the third.
  2. Line 5Four items.
  3. Line 6at(-1) counts from the end.
  4. Line 8Replace an item by assigning to its index.
  5. Line 10Reading past the end gives undefined, not an error.
Example 2

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(", ")}`);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Add to the end.
  2. Line 4Add to the start.
  3. Line 7Remove (and get back) the first item.
  4. Lines 10 to 11Find an item's position, then remove 1 item there.
  5. Line 13join turns the array into a readable string.
Example 3

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 5An array of arrays, forming a noughts and crosses board.
  2. Line 6First pick the row, then the column.
  3. Line 9slice() with no arguments makes a copy, so changing it doesn't affect the original.
  4. Line 13Spread ... combines arrays into a new one.

Common JavaScript Arrays Mistakes

Index starts at 1

Don't
const colors = ["red", "green", "blue"];
console.log(colors[1]); // "green", not "red"
Do
console.log(colors[0]); // "red"

Copying by assignment

Don't
const a = [1, 2];
const b = a;     // same array, two names!
b.push(3);
console.log(a);  // [1, 2, 3]
Do
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

Don't
[1, 2] === [1, 2]; // false
Do
JSON.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.

Fill in the blankseasy

Add "kiwi" to the end and remove the first item.

const fruit = ["apple", "pear"];
fruit.("kiwi");
fruit.();
console.log(fruit); // ["pear", "kiwi"]
Predict the outputeasy

What does this print?

const nums = [5, 10, 15];
console.log(nums.length, nums[nums.length - 1]);
Predict the outputmedium

What does this print?

const a = ["x"];
const b = a;
b.push("y");
console.log(a.length);
Fix the bugmedium

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(", "));
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Mon, Wed, Thu"

JavaScript Arrays Quiz

4 questions to check what you learned.

  1. What is the index of the first item in an array?

    • 0
    • 1
    • -1
    • It depends
  2. Which method removes the last item and returns it?

    • shift()
    • slice()
    • remove()
    • pop()
  3. What does ["a", "b"].indexOf("z") return?

    • 0
    • null
    • -1
    • false
  4. 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:

  1. Add "Dancing Queen" to the end
  2. Add "Bohemian Rhapsody" to the start
  3. Remove "Yellow" using indexOf + splice
  4. Log 4 songs: Bohemian Rhapsody, Hey Jude, Imagine, Dancing Queen
const playlist = ["Hey Jude", "Yellow", "Imagine"];
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Playlist is in the right order
  • Logs the summary