Working with Collections of Data: Arrays
An array is a list of values stored in order. Instead of making a variable for every item, you put the items in one array. Arrays are everywhere in JavaScript: lists of messages, products, names, or numbers.
const colors = ['red', 'green', 'blue'];
console.log(colors.length); // 3
console.log(colors[0]); // 'red'Reading and Changing Items
Each item has a position number called an index. Indexes start at 0, so the first item is [0], the second is [1], and so on.
const colors = ['red', 'green', 'blue'];
colors[1] = 'yellow'; // replace the second item
colors.push('purple'); // add to the end
colors.pop(); // remove the last item
console.log(colors); // ['red', 'yellow', 'blue']push adds an item to the end; pop removes and returns the last item.
A common mistake is reading past the end. colors[10] does not crash — it gives undefined.
Transforming Arrays: map and filter
Two methods do most everyday work with lists. Neither changes the original array; each returns a new array.
mapruns a function on every item and collects the results.filterkeeps only the items the function returns true for.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]Here n => n * 2 is an arrow function, a short way to write a function. It takes one number n and returns n * 2. The filter example uses %, the remainder operator: n % 2 === 0 is true when n is even.
Show diagram source
flowchart LR
A["[1, 2, 3, 4, 5]"] -->|map: n * 2| B["[2, 4, 6, 8, 10]"]
A -->|filter: even?| C["[2, 4]"]Looping with for...of
When you just want to visit each item — say, to log it — use a for...of loop. It runs the loop body once per item.
const names = ['Ada', 'Grace', 'Linus'];
for (const name of names) {
console.log(`Hello, ${name}!`);
}Use for...of for side effects like logging. Use map and filter when you want a new array as the result.
Choosing the Right Tool
| Goal | Use |
|---|---|
| Get one item | `colors[0]` |
| Add/remove at the end | `push` / `pop` |
| Build a new array of transformed items | `map` |
| Build a new array of matching items | `filter` |
| Visit each item for a side effect | `for...of` |
Exercise
Given const scores = [10, 25, 40];, write an expression that produces a new array with each score increased by 5, and state the value of scores.length afterwards.
Show answer
scores.map(s => s + 5) gives [15, 30, 45]. scores.length is still 3, because map returns a new array and does not change the original.
Exercise
What does const items = ['a', 'b']; items[5]; return, and why does it not throw an error?
Show answer
It returns undefined. JavaScript lets you read any index; indexes past the end simply have no value, so the result is undefined rather than an error.
Spotted a mistake, or code that does not work?