Destructuring in Javascript

The two most common data structures in Javascript, as in most languages, are objects and arrays. Javascript ES6 provides a useful syntax for unpacking objects and arrays into variables with assigned values. I’ll dig into some of those useful patterns here.

Let’s start off with arrays. The basic example shown here illustrates how easy it is to assign values to multiple variables in a single line of code. Each element in the array on the left is defined as a constant variable with a value equal to its matching element position in the array on the right.

What happens if the arrays are of different lengths? The additional variables are declared but are undefined.

We can also skip over variable declarations if we don’t have a value to assign to them.

Destructuring applies to any iterable and can be useful for applying to strings.

We can use the spread operator together with destructuring. In the example below we set variables for the first and last names and set all remaining elements equal to a variable called rest. That’s the common nomenclature but you can name it whatever you want.

We can also set default values for variables to use if no value is assigned.

The syntax for object destructuring looks similar: an object on the left equals an object on the right. The way it works is that the variable names declared in the object on the left have to match names of keys in the object on the right. Because it’s matching the variable name to key names the order of the variables is not significant in the same way it is with arrays.

It may seem somewhat limiting that the variable declaration name and the object key have to be an exact match. We can actually redefine variable declarations in the object on the left. In the example below I redefined city as place using the : syntax.

As with array destructuring we can also set default values for variable declarations.

Further, we can also use the spread operator when dealing with objects. In the example below the undeclared variables are stored in the rest object.


Is destructuring necessary? No. Does it make your code cleaner, more concise and legible? Yes, it certainly does.

Full-Stack Web Developer |

Full-Stack Web Developer |