3.12 Arrays
So far one variable holds one value. But in reality we often handle "a bunch" of data: all the students in a class, all the items in a cart, the seven days of a week. An array holds "an ordered list of values."
The lab below lets you add and remove elements, then see how map and filter transform them in bulk.
Create and access
Create an array with square brackets [], elements separated by commas:
const fruits = ["apple", "banana", "orange"];Access an element by its index — key point: indexing starts at 0!
fruits[0] // "apple" (first)
fruits[1] // "banana" (second)
fruits[2] // "orange" (third)
fruits.length // 3 (array length)Add and remove
const list = [1, 2, 3];
list.push(4); // add to the end → [1, 2, 3, 4]
list.pop(); // remove the last → [1, 2, 3]
list.unshift(0); // add to the front → [0, 1, 2, 3]
list.shift(); // remove the first → [1, 2, 3]Remember: push/pop work at the end, shift/unshift at the front.
Loop an array
Combined with last chapter's loops, you can process elements one by one:
const scores = [80, 92, 75];
for (const s of scores) {
console.log(s); // prints 80, 92, 75 in turn
}map and filter: an array's "superpowers"
These are two extremely common and elegant JS methods. Both return a new array without changing the original.
map: "transform" each element (same length):
const nums = [1, 2, 3];
const doubled = nums.map(x => x * 2); // [2, 4, 6]filter: "keep" elements by a condition (possibly shorter):
const nums = [1, 2, 3, 4, 5];
const big = nums.filter(x => x >= 3); // [3, 4, 5]Their argument is a function (an arrow function here). map passes each element to that function and collects the return values into a new array; filter keeps only elements for which the function returns true.