How to use arrays

Create and access an array

Array indexes begin at zero. length reports the number of elements.

const topics = ["values", "functions", "arrays"];
console.log(topics[0]);
console.log(topics.at(-1));
console.log(topics.length);

Add and remove items

push and pop operate at the end. These methods mutate the array.

const tasks = ["read"];
tasks.push("practice");
tasks.push("review");
const finishedLast = tasks.pop();
console.log(tasks, finishedLast);

Transform with map and filter

map creates one result per item; filter keeps matching items. Both return new arrays.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
const even = numbers.filter(number => number % 2 === 0);
console.log(doubled, even);

Find and summarize

find returns the first match or undefined. reduce combines values, though a loop can be clearer for complex work.

const prices = [3, 7, 12];
console.log(prices.find(price => price > 5));
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);