Complete JavaScript Course Module 6: Intermediate: Arrays

JavaScript Arrays: Create, Read and Update Lists

  • Beginner
  • Lesson 6.1
  • 5 min read
  • 24 of 76 in the course

In short

A JavaScript array is an ordered list of values stored in one variable. In this lesson you will learn how to create arrays, read items by index, and add or remove items. What is an array in JavaScript? So far, each variable you made held one value: one name, one price, one score.

A JavaScript array is an ordered list of values stored in one variable. In this lesson you will learn how to create arrays, read items by index, and add or remove items.

What is an array in JavaScript?

So far, each variable you made held one value: one name, one price, one score. But real programs work with lists all the time: a shopping cart, a list of messages, the songs in a playlist.

An array is a single value that holds many values in order. Think of it like a row of numbered boxes. Each box holds one item, and each box has a number so you can find it again.

You create an array with square brackets []. You separate the items with commas.

const fruits = ["apple", "banana", "cherry"];
const prices = [4.99, 12.5, 0.99];
const emptyCart = [];

console.log(fruits);
// Output: ["apple", "banana", "cherry"]
console.log(emptyCart);
// Output: []

The first line makes an array with three strings. The second holds three numbers. The third is an empty array, which is a normal starting point when you plan to add items later. Each item in an array is called an element.

An array can hold mixed types too: strings, numbers, booleans, even other arrays. In practice, most arrays hold one kind of thing, because that makes them easier to work with.

const mixed = ["Mia", 28, true, ["red", "blue"]];
console.log(mixed.length);
// Output: 4

How to read array items with an index

Every element has a position number called an index. JavaScript counts from 0, not 1. This is called zero-based indexing. So the first item is at index 0, the second at index 1, and so on.

You read an element by putting its index in square brackets after the array name. The length property tells you how many elements the array has.

const colors = ["red", "green", "blue", "yellow"];

console.log(colors[0]);            // Output: red
console.log(colors[2]);            // Output: blue
console.log(colors.length);        // Output: 4
console.log(colors[colors.length - 1]); // Output: yellow
console.log(colors[10]);           // Output: undefined
console.log(colors.at(-1));        // Output: yellow
console.log(colors.at(-2));        // Output: blue

Here is what each line does:

  • colors[0] gets the first element.
  • colors.length is 4, but the last index is 3, because counting starts at 0.
  • colors[colors.length - 1] is the classic way to get the last element.
  • Asking for an index that does not exist gives undefined. There is no error.
  • colors.at(-1) is the modern, shorter way to get the last element. Negative numbers count from the end.

Common mistake: Writing colors[colors.length] to get the last item. That index is one past the end, so you get undefined. Use colors.length - 1 or colors.at(-1).

You can also change an element by assigning to its index: colors[1] = "purple"; replaces "green" with "purple".

How to add and remove items: push, pop, shift and unshift

Arrays come with built-in methods, which are functions that belong to the array. Four of them add or remove items at the start or end.

MethodWhat it doesReturns
push(item)Adds to the endThe new length
pop()Removes from the endThe removed item
unshift(item)Adds to the startThe new length
shift()Removes from the startThe removed item

Let's use them on a to-do list:

const todos = ["Buy milk", "Call Sam"];

todos.push("Pay rent");
console.log(todos);
// Output: ["Buy milk", "Call Sam", "Pay rent"]

todos.unshift("Wake up");
console.log(todos);
// Output: ["Wake up", "Buy milk", "Call Sam", "Pay rent"]

const done = todos.pop();
console.log(done);   // Output: Pay rent

const first = todos.shift();
console.log(first);  // Output: Wake up
console.log(todos);  // Output: ["Buy milk", "Call Sam"]

push and unshift add items. pop and shift take one item out and give it back to you, so you can store it in a variable like done.

Tip: A simple way to remember: push and pop work at the end (like a stack of plates). shift and unshift work at the start.

How to check if an array contains a value

Often you need to ask "is this item in my list?" Use includes() for a yes/no answer, and indexOf() when you need the position.

const tags = ["html", "css", "javascript"];

console.log(tags.includes("css"));       // Output: true
console.log(tags.includes("python"));    // Output: false
console.log(tags.indexOf("javascript")); // Output: 2
console.log(tags.indexOf("python"));     // Output: -1

console.log(Array.isArray(tags));        // Output: true
console.log(Array.isArray("css"));       // Output: false
console.log(typeof tags);                // Output: object

indexOf returns -1 when the item is not found. Array.isArray() is the reliable way to check if something is an array, because typeof just says "object" for arrays.

Why can a const array still change?

You may be surprised that we used const and still changed the array with push. const means the variable cannot be reassigned to a new value. It does not freeze what is inside.

const cart = ["shoes"];
cart.push("socks");    // OK: we change the contents
console.log(cart);     // Output: ["shoes", "socks"]

cart = ["hat"];        // TypeError: Assignment to constant variable.

Think of const like a label glued to one box. You cannot move the label to a different box, but you can still put things in and take things out. Using const for arrays is the normal, recommended style.

Note: You can read more about every array method on MDN's Array reference.

Practice exercise

Create a const array called playlist with three song names. Then:

  1. Add a new song to the end and one to the start.
  2. Log the first and last songs (use at(-1) for the last one).
  3. Remove the first song and log which song was removed.
  4. Log whether your playlist includes a song of your choice.

Hint: You need push, unshift, shift and includes. Log playlist.length after each step to see how it changes.

Key takeaways

  • An array is an ordered list created with [], and each value is an element.
  • Indexes start at 0; the last index is length - 1, and at(-1) gets the last item.
  • push/pop work at the end, unshift/shift work at the start.
  • Use includes for yes/no checks, indexOf for positions, and Array.isArray to test for arrays.
  • A const array cannot be reassigned, but its contents can change.

Frequently asked questions

Why do JavaScript arrays start at 0?

The index means "how many steps from the start". The first item is zero steps away, so it is index 0. Most programming languages work this way.

Can a JavaScript array hold different data types?

Yes. One array can hold strings, numbers, booleans, objects and other arrays. It is usually clearer to keep one type per array.

What happens if I read an index that does not exist?

You get undefined. JavaScript does not throw an error, so check length or use includes when you are not sure.