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.

const [a,b,c] = [1,2,3]

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

const [a,b,c] = [1,2]

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

const [a,b,c] = [1, ,3]

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

const [firstName,lastName] = "Jordan Eckowitz".split(" ")

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.

const [firstName,lastName,...rest] = ["Nelson","Mandela","President","South Africa"]

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

const [username = "User", password = "Password"] = ["Jordan"]

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.

const me = {

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.

const me = {

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

const me = {

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.

const me = {

Conclusion

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

Full-Stack Web Developer | www.jordaneckowitz.com

Full-Stack Web Developer | www.jordaneckowitz.com