Destructuring in JavaScript

By Josephine Fischer

Josephine Fischer
Tech at Power

--

Destructuring makes it easier to work with objects, arrays and strings in JavaScript. Using a pattern syntax similar to object and array literals, we can poke into data structures and pick out the information we want into variables.

It will make your code simpler!

What is destructuring?

Let’s assume that the creating of objects, arrays and strings is called construction, destructuring will be the opposite of that — which is the extracting of values from objects, arrays or strings and assigning them to certain variables. However, you don’t always have to extract every value inside the object, array or string, just the ones you want to make use of.

It is important to note that destructuring is not the destruction of the array, object or string — the values stores in them will still be available. Destructuring only makes it easy to access these values by storing them in the variables.

Array destructuring:

If you want to assign the values of an array to separate variables, you can take advantage of destructuring to achieve your goal in a simple, clean way. No need to use indexes or loops!

We can assign the values inside of an array into variables like so:

Note that the position of the variables vs values is important here. The first new variable will always inherit the first value of the array.

However, even though the array literal destructure pattern is order-dependent, we can still pick and choose which elements of the array we want stored as variables by skipping indices:

Or we can do it like this with the rest operator:

Object destructuring:

The main difference between array and object destructing is the change in literal. In object destructuring, you make use of the object literal, which is the curly braces. This literal has to be on the left-hand side of the assignment operator.

Lets take a look at our previous example as an object:

When creating an object, we make use of key-value pairs. This technique comes in handy when destructuring — unlike in the case of an array, you do not need to always remember the position of the value (or pair) you want to destructure. As long as you are making use of the key to extract the value, the key will map to its assigned value in the object.

Here is how we would destructure our animals object:

As you can see with the example above, we used the same names for the variables as we did for the keys of the object. However we can define variables with names that differ from the keys:

One final note, we can also use deconstruction on strings like so:

Conclusion:

Destructuring is a handy tool to make use of as you write your code. It helps reduce the complexity of your code, making it more readable and human-friendly. Even if you prefer not to use it, understanding it cannot be overestimated due to its popularity.

This post is written by a Power Code Academy Student Developer.

--

--