What Is an Array?

Grade 7, page 1 of 14. A one-minute read.

Imagine you're keeping track of your favorite foods. With what you know so far, you'd do something like this:

JavaScript
const food1 = "burger";
const food2 = "omelet";
const food3 = "pancakes";
const food4 = "soup";

That's fine for four foods. But what about forty? Or the names of all 2,000 students in a school? Or every song in a playlist? You'd need thousands of variables. And how would you loop over them? You can't write food + i!

What you need is a single variable that can hold a whole list of values. In JavaScript, that's called an array.

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];
console.log(foods);

It prints

[ 'burger', 'omelet', 'pancakes', 'soup' ]

An array is written with square brackets [ ], with the items (also called elements) separated by commas. One variable, four values, in a nice tidy row.

Think of it like thisThe train

Think of an array as a train. The variable name (foods) is the name painted on the engine. Each item rides in its own carriage. The carriages are always in the same order, and each carriage has a number painted on it so you can find it.

An array is like a train: each carriage holds one value and has a number, starting at 0

Arrays can hold any type of value. Numbers, strings, booleans, even a mix (though mixing is usually a sign you should be using an object instead, which you'll learn in Grade 8):

JavaScript
const scores = [88, 92, 75, 64];
const answers = [true, false, true];
const mixedBag = ["hello", 42, true, null];
const empty = [];

console.log(scores);
console.log(answers);
console.log(mixedBag);
console.log(empty);

It prints

[ 88, 92, 75, 64 ]
[ true, false, true ]
[ 'hello', 42, true, null ]
[]

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning