Lists with Arrays

Storing many values in one place

9 min read · runnable Javascript

So far each variable held a single value. But what if you have a shopping list, or a group of scores? For that we use an array, which is an ordered list of values.

You create an array with square brackets [ ], separating each item with a comma.

let fruits = ["apple", "banana", "cherry"];
console.log(fruits);

Getting an item out

Each item has a position number called its index. Here is the surprising part: counting starts at 0, not 1.

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits[1]); // banana
console.log(fruits[2]); // cherry
Tip: The first item is always at index 0. This trips up almost everyone at first, so it is worth saying again: the count starts at zero.

How many items?

Every array knows its own length. Ask for it with .length:

console.log(fruits.length); // 3

Adding an item

You can add a new item to the end with .push:

fruits.push("date");
console.log(fruits); // apple, banana, cherry, date

Try it yourself

Run the code, then add another fruit of your choice.

Try it yourself
Output
Press “Run code” to see the result.

Quick check

Q1 In the array ["a", "b", "c"], what index does "a" have?

Q2 What does fruits.length tell you?

Want to save your progress? It's free.

Create a free account