Lesson 3 of 6 · 5 min
Arrays and objects
Store lists and records, loop over them, transform them with map, filter, find and reduce, and copy them safely with spread and destructuring.
On this page
Arrays hold ordered lists. Objects hold named properties. Together they can represent almost any data, and they are exactly what you get back from most APIs as JSON.
Arrays
const topics = ["HTML", "CSS", "JavaScript"]
topics[0] // "HTML" (indexes start at 0)
topics.length // 3
topics.at(-1) // "JavaScript" (the last item)
topics.push("SQL") // add to the end
topics.includes("CSS") // true
topics.indexOf("CSS") // 1
const stops you replacing the array, but you can still change what's inside it.
Loop over the items with for...of:
for (const topic of topics) {
console.log(topic)
}
Objects
const course = {
slug: "css",
title: "CSS Fundamentals",
lessons: 7,
tags: ["CSS", "Layout"],
}
course.title // "CSS Fundamentals"
course["slug"] // "css" (brackets work with any string, including variables)
course.lessons = 8 // change a property
course.level = "Beginner" // add one
delete course.level // remove one
Object.keys(course) // ["slug", "title", "lessons", "tags"]
Object.entries(course) // [["slug", "css"], ["title", ...], ...]
Reading a property that doesn't exist gives undefined. Use optional chaining to read deeply without crashing:
course.author?.name // undefined, not an error
Arrays of objects
Real data is usually a list of records:
const lessons = [
{ title: "How CSS works", minutes: 6, done: true },
{ title: "Selectors", minutes: 8, done: true },
{ title: "The box model", minutes: 7, done: false },
{ title: "Flexbox", minutes: 9, done: false },
]
The methods you will use every day
These return a new array or value and leave the original untouched.
// map: transform every item
const titles = lessons.map((l) => l.title)
// filter: keep the items that pass a test
const remaining = lessons.filter((l) => !l.done)
// find: the first item that passes, or undefined
const flexbox = lessons.find((l) => l.title === "Flexbox")
// some / every: does any / every item pass?
const started = lessons.some((l) => l.done) // true
const finished = lessons.every((l) => l.done) // false
// reduce: combine everything into one value
const totalMinutes = lessons.reduce((sum, l) => sum + l.minutes, 0) // 30
// chain them
const minutesLeft = lessons
.filter((l) => !l.done)
.reduce((sum, l) => sum + l.minutes, 0) // 16
Sorting
sort changes the array in place; toSorted returns a sorted copy:
const byLength = lessons.toSorted((a, b) => a.minutes - b.minutes)
const names = ["Neha", "asha", "Imran"].toSorted((a, b) => a.localeCompare(b))
Destructuring
Pull values out into variables:
const { title, minutes } = lessons[0]
const [first, second] = topics
function describe({ title, minutes = 5 }) {
return `${title} (${minutes} min)`
}
Spread: copy and combine
const more = [...topics, "Git"] // copy an array and add to it
const updated = { ...course, lessons: 9 } // copy an object and change one property
const merged = { ...defaults, ...userSettings } // later properties win
Copying instead of changing makes bugs easier to avoid, and it's how state is updated in frameworks like React. Spread copies only one level deep; use structuredClone(obj) for a full deep copy.
JSON
JSON is the text format APIs use. It looks like JavaScript objects with double-quoted keys:
const text = JSON.stringify(course) // object to string
const back = JSON.parse(text) // string to object
Try it
Using the lessons array above, log the titles of finished lessons, the total minutes, and a new array where every lesson has done: true (use map and spread, and check the original array is unchanged).
More from JavaScript Crash Course
- Lesson 5 · 5 minEventsRespond to clicks, typing and form submissions with addEventListener, use the event object, delegate events to a parent, and build a working theme toggle.
- Lesson 6 · 5 minAsync JavaScript and fetchWhy some code has to wait, promises, async and await, loading JSON from an API with fetch, handling errors and loading states, and running requests in parallel.
- Lesson 1 · 5 minValues and variablesNumbers, strings, booleans, null and undefined, let and const, template literals, and why you should always compare with ===.