Learn JavaScript · lesson 25 of 60 · about 7 minutes
Creating and Indexing Arrays
Show the guestbook on Sam's page: store many names in one array, and read them by their position.
What you'll learn
- Write array literals
- Read items by index
- Change items and check length
The guestbook
Sam's page gets a guestbook. The names of everyone who signed it are kept in one value, an array called guests, oldest first. The box under it shows how many names there are, the first one and the newest. That's what arrays are for: many values under one name, each at a numbered position.
Many values, one name
An array is an ordered list written in square brackets: ["read", "walk", "code"]. Like strings, positions start at 0, and .length gives the count.
The last item is always at arr.length - 1, or use arr.at(-1).
Reading items
const islands = ["Console Cove", "Branching Bayou", "Array Archipelago"];
console.log(islands[0]);
console.log(islands.length);
console.log(islands[islands.length - 1]);
console.log(islands.at(-1));Output
Console Cove
3
Array Archipelago
Array ArchipelagoChanging items
Assign to an index to replace an item. A const array can still have its items changed. const only stops you replacing the whole array.
Updating and printing
const scores = [10, 20, 30];
scores[1] = 25;
console.log(scores);
console.log(scores.join(" | "));
console.log(scores[5]);Output
[ 10, 25, 30 ]
10 | 25 | 30
undefinedTip
Reading a position that doesn't exist gives undefined rather than an error, so double-check your indexes.
Now try it yourself
This lesson is free in Codiqo, with 12 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.