Chapter 09
Arrays
A single variable holds one value. But often you have a list: all the items in a shopping cart, the scores in a game, the days of the week. An array is a single value that holds an ordered list of other values.
Creating an Array
Write the values inside square brackets [ ], separated by commas:
const fruits = ["apple", "banana", "cherry"];
const scores = [10, 8, 42, 7];
const mixed = ["Ada", 36, true]; // arrays can hold any types
console.log(fruits); // ["apple", "banana", "cherry"]Reading Items by Position
Each item has a position number called its index. Here's the crucial part that surprises everyone: counting starts at 0, not 1. So the first item is at index 0, the second at index 1, and so on. You read an item with square brackets:
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple" (the first)
console.log(fruits[1]); // "banana" (the second)
console.log(fruits[2]); // "cherry" (the third)
console.log(fruits.length); // 3 - how many itemslength - 1. For our 3 fruits that's index 2. Off-by-one mistakes here are a rite of passage - expect them and you'll catch them faster.Changing an Array
You can replace an item by assigning to its index, and add to the end with push:
const colors = ["red", "green"];
colors[1] = "blue"; // replace the second item
console.log(colors); // ["red", "blue"]
colors.push("yellow"); // add to the end
console.log(colors); // ["red", "blue", "yellow"]
const removed = colors.pop(); // remove the last item and hand it back
console.log(removed); // "yellow"colors is a const. const only stops you replacing the whole array with a different one; it doesn't freeze the items inside. That's fine and normal.Looping Over an Array
Arrays and loops are best friends. To do something with every item, for...of is the cleanest way - it hands you each item in turn:
const scores = [10, 8, 42, 7];
for (const score of scores) {
console.log(score);
}
// 10 8 42 7You can combine everything you've learned. Here we add up a list of numbers with a function and a loop:
function total(numbers) {
let sum = 0;
for (const n of numbers) {
sum = sum + n;
}
return sum;
}
console.log(total([10, 8, 42, 7])); // 67Powerful Shortcuts
Arrays have built-in methods that loop for you. Two you'll love: filter keeps only the items that pass a test, and map transforms every item into a new one. Each takes a function that runs once per item:
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10, 12]Don't worry about mastering these yet - just know they exist. That n => n * 2 is a compact way to write a function (an "arrow function"): take n, give back n * 2. You'll see them everywhere in real JavaScript.