4. Arrays, objects & destructuring
JavaScript · 56 pages source format
Arrays hold ordered lists. Objects hold keyed records. map, filter, find, reduce, and some replace index loops for most tasks. Destructuring and spread make copying and unpacking elegant. JSON.parse/stringify connects JS to APIs.
What you'll learn
- Array methods
- Object literals & shorthand
- Destructuring & spread
- JSON
- Optional chaining
Array essentials
push/pop/shift/unshift mutate. map/filter/reduce return new arrays — prefer these. find returns first match; some/every return booleans.
const users = [
{ name: "Ava", active: true },
{ name: "Ben", active: false },
{ name: "Cal", active: true },
]
const activeNames = users
.filter(u => u.active)
.map(u => u.name)
const firstActive = users.find(u => u.active)Do this now
Given users = [{name:"Ava",active:true},{name:"Ben",active:false}], filter active, map names, find first active.
reduce for aggregation
reduce accumulates a single value — sums, counts, grouping. The Swiss Army knife when map/filter are not enough.
Do this now
Use reduce to count how many users are active. Then group users by active status into {true: [...], false: [...]}.
Objects and shorthand
Property shorthand: {name} instead of {name: name}. Computed keys: {[key]: value}. Object spread {...obj} for shallow copy.
const product = { id: 1, name: "Widget", price: 9.99 }
const updated = { ...product, price: 12.99 }
// product.price still 9.99Do this now
Create a product object with id, name, price. Clone it with spread, change price on clone, verify original unchanged.
Destructuring
Unpack arrays: const [first, ...rest] = arr. Unpack objects: const {name, age} = user. Default values in destructuring prevent undefined surprises.
Do this now
Destructure name and email from a user object. Swap two variables using destructuring.
JSON and optional chaining
JSON.stringify(obj) and JSON.parse(str) for serialization. Optional chaining ?. and nullish coalescing ?? prevent "cannot read property of undefined" crashes.
const json = JSON.stringify(users)
const parsed = JSON.parse(json)
const city = parsed[0]?.address?.city ?? "Unknown"Do this now
Serialize users to JSON, parse back, access user?.address?.city ?? "Unknown".