The other day I reached for destructuring assignment when I wanted to grab just a single property from an HTTP response. This syntax makes it possible for one to unpack values/properties from arrays/objects and assign them to distinct variables. Let's look at why it's such a handy expression!

To keep it simple, we'll use the following object in all the examples:

const response = {
    status: 200,
    data: [
        {id: 1, name: 'Ben Comeau'},
        {id: 2, name: 'Jane Doe'}
    ],
    path: 'query-endpoint',
    total: 125,
    pages: {
        next: 4,
        previous: 2
    }
}

Single values

First, let's say you wanted to grab just the status off the response object. Typically one would approach it like this:

let status = response.status

Alternatively, using the destructuring assignment syntax, we can grab it like this:

let { status } = response

Multiple values

You may be wondering, "Why? Why not just use the first option?" And I think for this example you'd be right in questioning it. But what about when you'd like to grab data and total, too? We know it would usually look like this:

let status = response.status
let data = response.data
let total = response.total

Now let's see how we'd do this using destructuring assignment syntax:

let { status, data, total } = response

Awesome! Much cleaner and to me, more readable once you're familiar with the syntax. And this is just the tip of the iceberg, really. Let's check out two more cases which I often use.

Nested properties

Notice that the pages property is an object – let's use our new syntax to grab one of its values:

let { pages: { next } } = response // 4

This assigns the response.pages.next value to next – pretty handy! But what if you're trying to use this to assign the value to an existing variable? Or a class property?

Assignment without declaration

Let's grab that same response.pages.next value but instead assign it to an imaginary class' next property:

({
    pages: {
        next: this.next // Notice to where we're assigning the value!
    }
} = response )

Slightly different syntax as before, but the concept remains the same. Super helpful when dealing with existing objects or class instances.

I highly recommend reading the MDN docs for more examples of this great feature!