Destructuring: Arrays & Objects

Mickey Martinez
Mickey Martinez
July 28, 2020
a neon sign in the middle of a room

A special JavaScript syntax introduced in ES6 is the Destructuring assignment, which gives us the ability to DO MORE by doing less. Destructuring is used to more easily assign values taken directly from an object or an array.

Let’s start by taking a look at an example of an object and the process required to extract its values prior to ES6:

var obj = {first: ‘Rick’, last: ‘Sanchez’, age: 70}; var first = obj.first; var last = obj.last;

Destructuring saves us from repeating ourselves like above — eliminating the need to create two separate variables to extract the first and last values from the object using dot notation.

By using ES6 destructuring syntax we can create an equivalent assignment statement:

const { first, last } = obj; // first = 'Rick', last = ‘Sanchez’

Above, the first and last variables will be created on the left hand side, and then assigned to the corresponding values from the obj object.

This is where destructuring has really provided significant impact — It lets you extract multiple properties from an object, which wasn’t possible to do all at once prior to ES6. In practice, destructuring will also help significantly reduce the amount of code you write.

So you might be thinking, “that all seems pretty easy.” While true, the challenge with destructuring is that there’s so many different ways of going about doing it, and so many combinations of the syntax.

To dive a bit deeper — snorkeling depth — we can look through some key examples of destructuring both arrays and objects. This will help establish a solid foundation for eventually leveraging destructuring to perform list transformations, assigning default values, swapping, ignoring values, nested arrays, and more.

Destructuring Arrays

Variable declarations when destructuring:

const [first, second] = [true, false];first = true second = false


[first, second] = [true, false];

With array destructuring, you can create new variables using an item in the array as a value. Let’s look at an example of an array with the various parts of a date:

const date = ['11', '02', '1982'] // values represent month, day, year

Arrays in JavaScript will always maintain their order, so in our example above the first index will always be a month, the second will be the day, and third the year. With this in mind, you could create variables from the items in the array using bracket notation:

// Process before destructuring was introduced const month = date[0] const day = date[1] const year = date[2]

Continuing to manually do this will bloat your code. Cue array destructing — where instead we can assign the values from the array in order, all on one line, and immediately assign them to their own variables:

// Destructure array values into variables const [month, day, year] = dateconsole.log(month) // 11 console.log(day) // 02 console.log(year) // 1982

You can even skip/omit values in the array by using a comma and leaving the syntax blank:

// Skips the second item in the array const [month, , year] = dateconsole.log(month) // 11 console.log(year) // 1982

Below is a helpful visual example of what we just covered above. I’ve also included an example of destructuring with the spread operator, and swapping variables without needing to use temp variables — these begin to show how you can really leverage destructuring.

Destructuring Objects

As we first touched on at the start of this post, destructuring is equally as valuable on objects.

You can extract as many or as few values from an object as you need. As a refresher, let’s first look at how we declare variables on the left hand side, and match them to the properties of the object on the right hand side.

Variable declarations:

// create new variables using an object property as the value const {first, second} = {first: 0, second: 1}; first = 0 second = 1


{first, second} = first: 0, second: 1};

Now, with a solid understanding of variable assignment, let’s take a look at the first two examples in the image below. These highlight how destructuring allows you to assign a new variable name when extracting values, by putting the new name of the variable after a colon {user: x}.

In the second example we see a common mistake, where the property name doesn’t match the original on the right, so when we log out the newly declared variable x, a value of undefined is returned. This issue is resolved in the last example, which illustrates how to properly reassign values when destructuring.

Destructuring Objects & Arrays

Now let’s observe how we can combine both object and array destructuring into a single destructuring assignment. First let’s look an an object that also has an array of data. We start by declaring the blog object.

// Declare the blog object const blog = { title: 'My First Space Travel Blog', author: { firstName: 'Rick', lastName: 'Sanchez', }, tags: ['ideas', 'notes', 'inter dimensional travel'], }

Then we destructure as needed:

const { title, author: { firstName, lastName }, tags: [ideasTag, notesTag, travelTag], } = blog;console.log(title) // My First Space Travel Blog

Now let’s take those same principals, and look at another nested data structure that’s an array of objects. The goal is to destructure this nested data structure into two variables, one variable should have the string 'blue' and the other 'yellow'.

var friends = [ { name: 'Rick', color: 'blue' }, { name: "Morty", color: 'yellow' } ];

Remember, without destructuring we’d need to separately assign the values to two variables:

// Without destructuring const firstColor = friends[0].color; const secondColor = friends[1].color;

With destructuring, we can do the same variable assignment two different ways:

let [ color1, color2 ] = [friends[0].color, friends[1].color]; // OR let [{ color: firstColor }, { color: secondColor }] = friends; // Assigning blue to firstColor and yellow to secondColor.

Use Destructuring to Pass an Object as a Function’s Parameters

What happens when we have a data structure and leverage destructuring to pass an object as the parameters of a function? At times you can destructure the object in a function argument itself:

const profileData = { name: 'Morty', age: 14, nationality: 'American', location: 'Dimension C-137', email: '', 'last login': 'Tuesday' };const profileUpdate = (profileData) => { const { name, age, nationality, location } = profileData; // do something with the variables }

This effectively destructures the object sent into the function. This can also be done in-place:

const profileUpdate = ({ name, age, nationality, location }) => { // do something with the variables }

Destructuring in-place removes extra lines and further cleans up our code. Additionally, we avoid having to manipulate an entire object inside a function, and can select just the fields that are needed to be copied inside the function.

Hopefully by now you’ve begun to understand how the ES6 destructuring assignment adds desired functionality to JavaScript and produces more succinct code. In practice you’ll gain an appreciation for destructuring, especially when dealing with complex objects or arrays, and you’re able to manipulate their data quickly.

Share this post
Related Posts:

Interested in working with us?

Give us some details about your project, and our team will be in touch with how we can help.