Destructuring in JavaScript

Written by Tom Wilkins
Sat, 25 Jan 2020

Write cleaner code by destructuring arrays, objects and strings!

Destructuring in JavaScript

In this post, I'll explain how destructuring can be used to work with elements/properties in arrays, objects and even strings. Using this technique can make your code cleaner, easier to follow and more type safe.

What is destructuring?

Simply put, destructuring is where you access elements of a data structure and assign them to variables inline. We'll go through several examples in this post to help demonstrate how this works, and why you might want to use it.

Destructuring objects

Let's begin with an object that represents a person:

const person = {
firstname: "John",
surname: "Doe",
dob: "1989-05-01",
gender: "male"
};

Perhaps I want to take the date of birth for this person to figure out their age. I could access their date of birth like this:

const dob = person.dob;

This is fine, but there's a bit of repetition going on. With destructuring, I don't need to write dob twice:

const { dob } = person;

This becomes particularly powerful when you want to access multiple properties:

// without destructuring
const firstname = person.firstname;
const surname = person.surname;
const dob = person.dob;
const gender = person.gender;

// with destructuring
const { firstname, surname, dob, gender } = person;

An advantage that is a real plus for clean code is that you are more likely to use consistent names for such properties. In the example without destructuring, you may be tempted to use different variable names which can get confusing for people reading your code (including your future self!).

However, sometimes you do need to use alternative names - and that's something you can do in destructuring with aliases, like so:

const { firstname: name } = person;

Here we are taking the firstname property and assigning to a variable called name.

Nested destructuring

Let's add some more complexity to the person object:

const person = {
firstname: "John",
surname: "Doe",
dob: "1989-05-01",
gender: "male",
address: {
number: 1,
street: "Example St.",
town: "Exampleton",
postcode: "EX4 9LE"
}
};

If we want to access the postcode from inside the address, together with the firstname and surname, we can do so like this:

const {
firstname,
surname,
address: { postcode }
} = person;

This may look similar to the aliasing shown earlier, but the extra curly braces show that we are accessing properties inside address, rather than aliasing it.

An alternative would be to destructure twice:

const { firstname, surname, address } = person;
const { postcode } = address;

For some, this may be more readable. However, we've used an extra line and also now have an address variable that we didn't really need. With larger objects, in larger applications this could be a problem.

Destructuring Arrays

Destructuring can also be used on arrays! The main difference is that unlike objects, elements inside arrays are set at an index, rather than a key - so we do have to think up variable names for the elements we extract from the array.

Let's demonstrate with an array:

const people = [
{
name: "John Doe",
title: "Mr"
},
{
name: "Jane Doe",
title: "Mrs"
}
];

const [john, jane] = people;

With arrays, you place your variable names where the corresponding elements appear in the array.

What if you don't want all elements of the array?

1. Treat the array as an object.

In JavaScript, arrays are objects! This means you can access an array index like this and use aliasing to give it a sensible name:

const { 1: jane } = people;

2. Don't use destructuring!

Just because you can use an exciting new feature to do something, doesn't mean you should. This way works and will make sense to people reading it:

const jane = people[1];

Destructuring Strings

Destructuring can also be used on strings! Let's use it to format a country name and capitalise the first letter.

const [first, ...rest] = "england";
const england = first.toUpperCase() + rest.join("").toLowerCase();

The first statement assigns the first character to the variable first, and uses the rest (...) operator to assign all other characters to the variable rest - this variable will be an array of characters.

The second statement ensures the first character is set to upper case, and then joins the array of remaining characters together and ensures they are set to lower case.

Advantages of destructuring

For me, the biggest advantage is the naming consistency it encourages while removing a lot of repetition. When assigning variables to properties on objects, it makes it easier to follow if they are named the same way - this is more tedious to write without destructuring due to all the repetition shown in the example above, and developers might be tempted to shorten variable names, which is where inconsistency can creep in.

Disadvantages of destructuring

Browser support

If you have to support older browsers, this feature may not be available. However, if your source code runs through a compiler for production such as Babel, you can use destructuring which will transpile to something older browsers can understand (most likely the repetitive example above). The real benefits of destructuring are in the writing and reading of the code rather than runtime performance, so it's a perfect case for a transpiler.

Scoping conflicts

If you have an object with properties that have the same names as other variables within the same scope you'll have to use aliasing to use them. However, if you do run into this, you ought to question whether your variables and object properties are aptly named.

Further Reading

If destructuring looks like something you would enjoy using, I'd also recommend looking at the ...spread and ...rest operators. They are loosely related and the latter was mentioned briefly in this post.

Thank you for reading

You have reached the end of this blog post. If you have found it useful, feel free to share it on Twitter using the button below.

Tags: TIL, JavaScript, Blog, Destructuring, Objects, Arrays