Intro to Destructuring Objects (ES6)

Posted on Jun 1, 2015

Destructuring is a feature of the ES6 spec that allows you to write less code to “data-proof” your functions. You can simultaneously declare variables while pulling them out of an object. Ultimately, I think it leads to more readable code by removing the repetition of a common pattern.

There are a number of options for destructuring an object. The basic syntax looks like this:

This will automatically create variables as declared in the curly braces on the left. It will also pull out the properties of the object on the right and assign the values to the associated variables on the left.

Though this is the first time we have seen curly braces on the left side of an assignment operator in JavaScript, this is actually valid syntax according to MDN.

It may make more sense in the context of a common example, such as an Ajax or http request, which returns an object of data.

Let’s pretend that the function below called getDeets() is an http request. Rather than pulling apart the data object that is returned and either using copious amounts of dot notation or individually assigning it’s properties to variables, we can clean it up with this syntax. The following two code examples produce the same result.

Traditional Syntax

With ES6 Destructuring


Fortunately, you are not bound to property names of the object you are working with. You can assign new variable names to the object you are destructuring. Perhaps you want to create shorter variables. You can assign variable names by providing a value using the syntax show below.

As Parameters

There is an additional step we can take to make our destructuring even more concise. We can destructure our objects when we declare our functions. If we have an object, we can pass that to a function and tell our function to destructure in the parameters.

Default Values

We often spend a lot of time in data proofing our functions to do things like this:

Wouldn’t it be cool if we could use destructuring to remove that boilerplate? Yes, it would be cool. So cool, in fact, that ECMA decided that you should be able to do it. So you can declare default values like this:

Submit a Comment

Your email address will not be published. Required fields are marked *

echo date("Y");