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.
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"]
Explore an array
Type items separated by commas, then use the buttons to see what happens. Watch the indexes update.
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"];
A JavaScript array example
Arrays in JavaScript can grow and shrink. This program shows a few common array methods.
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.