Arrays
An array is a list inside square brackets, separated by commas. Each item has a position called an index. Indexes start at 0, not 1.
const fruits = ["apple", "pear", "plum"];
console.log(fruits[0]);
console.log(fruits[2]);
console.log(fruits.length);apple plum 3
.length tells you how many items there are. Because indexes start at 0, the last item is always at length - 1.
Try it
What does this print?
const nums = [10, 20, 30];
console.log(nums[1]);
Adding to an array
.push() adds an item to the end. Even though the array was made with const, you can still change what's inside it. const only stops you from replacing the whole array.
const list = [1, 2];
list.push(3);
console.log(list);
console.log(list.length);[ 1, 2, 3 ] 3
Looping over an array
for...of gives you each item in turn, so you don't need a counter.
const names = ["Ana", "Ben", "Cy"];
for (const name of names) {
console.log("Hi, " + name);
}Hi, Ana Hi, Ben Hi, Cy
Try it
What does this print?
const a = [1, 2];
a.push(3);
console.log(a.length);
Objects
An object stores values under names, called keys. You write it with curly braces. Each key is followed by a colon and its value.
const pet = {
name: "Rex",
age: 3
};
console.log(pet.name);
pet.age = 4;
console.log(pet.age);Rex 4
You read a value with a dot and the key. You can also write pet["name"], which is useful when the key is stored in a variable.
Try it
What does this print?
const point = { x: 1, y: 2 };
console.log(point.z);
Lists of objects
Arrays and objects are often used together. Here's a list of players, each with a name and a score.
const players = [
{ name: "Ana", score: 12 },
{ name: "Ben", score: 9 }
];
for (const p of players) {
console.log(p.name + ": " + p.score);
}Ana: 12 Ben: 9
Common mistakes
The first item is at index 0. Asking for fruits[3] in a three-item list gives undefined.
pet.nmae doesn't cause an error. It quietly gives undefined, which can be hard to spot.
A const array can still have items pushed into it. const only stops you from replacing it with a different array.
Recap
- Arrays are ordered lists. Indexes start at 0.
- .length is the number of items. .push() adds one to the end.
- Objects store values under keys.
- A missing index or key gives undefined.