Please enable JavaScript to use CodeHS

JavaScript Basics

Arrays in JavaScript

An array is a list of values stored in one variable. Learn to create, read, and change arrays in JavaScript.

Beginner ~10 min All
The Big Idea

Store many values in one variable

An array is a list of values stored together. Instead of creating one variable for every item, you can put them all in an array and work with the whole list.

In JavaScript, an array looks like this:

var groceries = ["apples", "bread", "milk"];

Arrays are useful when you want to keep related items together, like names, scores, or colors.


How It Works

Creating and using arrays

You can create an array with square brackets []. Each item is separated by a comma.

var colors = ["red", "green", "blue"];
var numbers = [10, 20, 30, 40];

Each item has a position called an index. Indexes start at 0. So colors[0] is "red" and colors[1] is "green".

console.log(colors[0]); // red
colors[1] = "purple";
console.log(colors); // ["red", "purple", "blue"]

Arrays have special functions called methods. Two common ones are push to add an item to the end and pop to remove the last item.

colors.push("yellow");
console.log(colors); // ["red", "purple", "blue", "yellow"]

colors.pop();
console.log(colors); // ["red", "purple", "blue"]

Interactive

Explore an array

Type items separated by commas, then use the buttons to see what happens. Watch the indexes update.


Your Turn

Check yourself

Write a short JavaScript array that holds the names of three pets or animals you like.

Sample answer: var pets = ["dog", "cat", "rabbit"];


Code

A JavaScript array example

Arrays in JavaScript can grow and shrink. This program shows a few common array methods.


Check Yourself

Quick quiz

1. What is an array?

2. What is the index of the first item?

3. What does push do?

Keep learning

You can store lists in JavaScript. Next, see how arrays work in Java.