Destructuring in JavaScript

Xander Reynolds
4 min readJun 3, 2021

Destructuring is a useful tool in JavaScript that can make code more concise and more readable (That’s a win win!). This is a page out of the functional programmers handbook called pattern matching. Pattern matching can be described like a switch statement to match conditions to different behaviors. This is not a complete definition, but is a simple way of explaining pattern matching.

Maybe a quick example from a functional language called elixir just for fun:

def load(filename) do  case File.read(filename) do    {:ok, binary} -> :erlang.binary_to_term binary    {:error, _reason} -> "That file does not exist"  endend

The function is trying to load a file, and based on the result will either return the binary data, or a string that says the file does not exist. I like this type of function because all paths can be visualized and are concisely described (okay, I know the syntax may be a little confusing, but if you know the language it is very straightforward.). This can also be done with arrays in elixir.

def mirror_row(row) do  [first, second, _tail] = row  row ++ [second, first]end

In this case, it assigns the first two array indexes to the variables ‘first’, and ‘second’ and the tail is the rest. This is reminiscent of an older languages like Prolog (started about 1972) also used these ideas (pattern matching) for things like artificial intelligence.

Okay, enough with the history lessons and comparisons, let’s get back on topic at hand. Destructuring with JavaScript.

Basic Object Destructuring

Let’s say you have a person with a name and some hobbies.

let Person = {
firstName: "Billy",
lastName: "Jones",
hobbies: ['hiking', 'canoeing', 'swimming', 'flying'],
}

Let’s say you want to get the name from the person. This can be done with the old fashioned way:

const firstName = Person.firstName; //firstName = "Billy"

Or with destructuring,

const {firstName} = Person; //firstName = "Billy"

After this call, the new variable ‘firstName’ will have the value “Billy”. This can also be done with multiple object properties:

const {firstName, lastName} = Person; 
//firstName = "Billy", lastName = "Jones"

Now there are new variables called ‘firstName’ and ‘LastName’ with the values from the Person object. It saves a little space and is a little cleaner (especially if the object has a lot of properties like from an API call.

Let’s say we have this person now and we want to get the city out of the person.

let Person = {
firstName: "Billy",
lastName: "Jones",
hobbies: ['hiking', 'canoeing', 'swimming', 'flying'],
location: {
city: 'cincinnati'
}
}
const { location: {city} } = Person;
//city = 'cincinnati'

This works with arrays too and not just basic types:

let Person = {
firstName: "Billy",
lastName: "Jones",
hobbies: ['hiking', 'canoeing', 'swimming', 'flying'],
}
let {hobbies} = Person;
//hobbies: ['hiking', 'canoeing', 'swimming', 'flying']

If you don’t like the property name, and you want to use your own new variable name, this can be done with an alias.

let Person = {
firstName: "Billy",
lastName: "Jones",
}
const { firstName: name } = Person;
// name = "Billy"

We can also do a combination of destructuring this with objects/arrays. What if we wanted to get the first Hobby of the person. This can also be done with destructuring. Let’s take a look at a quick array example:

let hobbies: ['hiking', 'canoeing', 'swimming', 'flying'];
const [firstHobby, ...rest] = hobbies;
//firstHobby = 'hiking', rest = 'canoeing', 'swimming', 'flying'

What is happening here? The array is being split into different variables ‘firstHobby’ and ‘rest’. The firstHobby contains the first value in the array which in this case is hiking. the ‘…’ before the second variable is called the spread operator. It tells the software to put the rest of the information in this variable.

This can be combined with the object destructuring as well.

let Person = {
firstName: "Billy",
lastName: "Jones",
hobbies: ['hiking', 'canoeing', 'swimming', 'flying'],
}
let {hobbies: [firstHobby, ...rest]} = Person1;
//firstHobby = 'hiking'

What is happenning here? First, it is getting the ‘hobbies’ property from the Person and has this array. Then it is destructuring the array it into two parts, ‘firstHobby’ and ‘rest’.

Let me give another example where this can be useful. Let’s say you have an array of people and want to get all their first names:

let Person1 = {
firstName: "Billy",
lastName: "Jones",
}
let Person2 = {
firstName: "Jane",
lastName: "Jones",
}
let Person3 = {
firstName: "Bobby",
lastName: "Jones",
}
let Person4 = {
firstName: "James",
lastName: "Jones",
}
const family = [Person1, Person2, Person3, Person4];for(const {firstName} of family){
console.log(firstName);
}
//logs: Billy, Jane, Bobby, James

Destructuring with functions arguments

This can be useful too with functions. It is possible to pass an object but only care about one property. In this case we can

let Person = {
firstName: "Billy",
lastName: "Jones",
}
const logFirstName = ({firstName}) => {
console.log(firstName);
}
logFirstName(Person);
//logs: 'Billy'

This is convenient way to grab one or more properties from the object that is needed in the method.

Have you found a use for destructuring in your code? Let me know, I would like to see how you are using it! Happy Coding!

--

--