First Principles
Programming

Object Destructuring in Javascript

Pulling properties out of objects into variables — with renaming, default values, nested objects, and function parameters.

By Fadjar Rafi. Published 29 Sept 2024. 2 min read.

Contents
  1. The basics
  2. A few useful patterns

Destructuring is a shorthand for pulling properties out of an object and into their own variables. Instead of reaching for each property one at a time, you grab what you need in a single line.

Say we have an apple object with name, color, weight, and taste:

const apple = {
  name: 'Apple',
  color: 'Red',
  weight: 150,
  taste: 'Sweet',
}

Without destructuring, you'd assign each property on its own line:

const name = apple.name // 'Apple'
const color = apple.color // 'Red'
const weight = apple.weight // 150
const taste = apple.taste // 'Sweet'

That gets tedious fast, especially with larger or nested objects like the JSON you get back from an API.

The basics#

Here's the same thing with destructuring — one line does it:

const { name, color, weight } = apple

console.log(name) // 'Apple'
console.log(color) // 'Red'

Each variable takes the value of the matching property in apple.

Properties of an apple object being extracted into separate variables

A few useful patterns#

Renaming#

Give the variable a different name with a colon:

const { name: fruitName, color: fruitColor } = apple

console.log(fruitName) // 'Apple'
console.log(fruitColor) // 'Red'

Default values#

If a property doesn't exist, the variable is undefined. You can set a fallback:

const { size = 'Medium' } = apple

console.log(size) // 'Medium'

Since apple has no size, the default kicks in.

Nested objects#

You can reach into nested objects too — handy for API responses:

const fruit = {
  name: 'Apple',
  nutrients: {
    vitamin_c: 4.6,
    fiber: 2.4,
  },
}

const {
  nutrients: { vitamin_c, fiber },
} = fruit

console.log(vitamin_c) // 4.6
console.log(fiber) // 2.4

Function parameters#

Destructuring works right in the parameter list, so a function can pull out just the fields it needs:

function describeFruit({ name, color, taste }) {
  return `The ${name} is ${color} and tastes ${taste}.`
}

describeFruit(apple) // 'The Apple is Red and tastes Sweet.'

That's most of what you'll reach for day to day. Once it clicks, you'll use it everywhere — API responses, function arguments, imports.