Arrays

Destructuring Objects and Arrays in JavaScript

Learn how to use JavaScript destructuring to pull values out of objects and arrays into named variables, rename them, and skip array items you do not need.

Destructuring pulls values out of objects and arrays into named variables in one step.

Given an object:

const person = {
  firstName: 'Tom',
  lastName: 'Cruise',
  actor: true,
  age: 54 //made up
}

const { firstName: name, age } = person //name: Tom, age: 54

name and age hold the extracted values.

The property is still called firstName. Only the local variable is renamed. Add a default for a missing or undefined property:

const { role = 'member' } = person

A default does not replace null, because null is an explicit value. Destructuring null or undefined as an object throws, so validate an uncertain input before destructuring it.

The syntax also works on arrays:

const a = [1, 2, 3, 4, 5]
const [first, second] = a

Skip positions with empty slots:

const [first, second, , , fifth] = a

Object destructuring follows property names. Array destructuring follows position. Object shapes survive reordering better when callers should not depend on index order.

Destructuring shines at function boundaries:

function formatUser({ name, city = 'Unknown' }) {
  return `${name}, ${city}`
}

It does not clone nested data. Variables still refer to the same nested objects:

const user = { settings: { theme: 'dark' } }
const { settings } = user
settings.theme = 'light'
console.log(user.settings.theme) // light

Swap variables without a temporary using destructuring:

let a = 1
let b = 2
;[a, b] = [b, a]
console.log(a, b) // 2 1

Function parameters can destructure too:

function printCoords({ x, y }) {
  console.log(x, y)
}

Rename while destructuring when API field names do not match your variables:

const { createdAt: publishedAt } = post

Provide defaults for optional API fields so callers do not need defensive checks on every access:

const { title = 'Untitled', tags = [] } = post

Nested destructuring works too: const { user: { name } } = session. Keep the shapes shallow when you can. Deep paths fail fast when any intermediate value is missing.

Rest in objects omits keys you do not want to forward: const { password, token, ...safe } = account.

Validate before destructuring when input comes from the network. const { id } = null throws immediately.

Destructure an API response with a renamed ID field, a default label, and a rest object. Pass null into the same function and decide where validation should happen.

Lesson completed