DEV Community

Cover image for Destructuring Arrays and Objects in ES6
Mike Conner
Mike Conner

Posted on

Destructuring Arrays and Objects in ES6

There are already so many ways to navigate, modify, create, and otherwise interact with arrays and objects. Its only natural that some of them might slip your mind from time to time. Destructuring is one such method that, while not exactly hard or complicated, might not be your first thought when you're thinking of ways to interact with an object or array. Today, I'm going to go over exactly what destructuring is and how to do it, and hopefully, you'll be able to implement destructuring to write cleaner, more concise code in the future!

What is destructuring?

In the simplest terms, destructuring is just a way to assign values to new variables. The beauty of destructuring is that this assignment very closely mimics the data structure that the values are being grabbed from. Confused? It'll all make sense once we look at some examples.

Arrays

We'll start by looking at some different ways to use destructuring on arrays.

let hobbitses = ['Frodo', 'Sam', 'Merry', 'Pippin'];

Here, we have created an array. Suppose we want to create new variables with values equal to each one of the elements of the array. In traditional JavaScript, that could look something like this:

let baggins = hobbitses[0], gamgee = hobbitses[1], 
    brandybuck = hobbitses[2], took = hobbitses[3];

Not exactly hard, but not very elegant. Lets see how that would look using destructuring assignment:

let [baggins, gamgee, brandybuck, took] = hobbitses;
console.log(baggins); // prints 'Frodo'
console.log(brandybuck); // prints 'Merry'

Much simpler, right? We can see that the the variable names to be assigned are now encased in array literals to the left of the equal sign, with the array containing the values on the right. I can already hear you asking "but what if I don't want to assign variables to every element of the array?" Don't worry, destructuring has you covered there too. Say you only want to assign values to the first two elements:

[baggins, gamgee] = hobbitses;
console.log(gamgee); // prints 'Sam'

Easy! Just declare two variables, and only two will be assigned. The rest of the array will be ignored. Also, notice that in the example above, we didn't ACTUALLY declare any variables, we just reassigned already-existing ones. Destructuring can handle that too! Thats all well and good, but what if you wanted to skip over some of the elements? We can do that too:

[baggins,, brandybuck] = hobbitses;
console.log(baggins); // prints 'Frodo'
console.log(brandybuck); // prints 'Merry'

[baggins,,, took] = hobbitses;
console.log(took); // prints 'Pippin'

[,,,took] = hobbitses;
console.log(took); // prints 'Pippin'

Notice that for each additional comma after the first comma, we skip an element of the array. If nothing precedes the first comma, as in the final example above, we start off skipping elements. Theres one more destructuring trick you can add to your array arsenal, declaring trailing items:

let [mordor1, mordor2, ...isengard] = hobbitses;
console.log(isengard); // prints '["Merry", "Pippin"]

In the above example, we've assigned the first two variables normally. However, The third variable is preceded by the spread operator. This means that everything else in the hobbitses array that hasn't yet been assigned will be put in an array with the name "isengard". Handy! Now lets take a look at how we can use destructuring with objects.

Objects

When we destructure objects, we're typically trying to bind variables to the values associated with properties of said object. Again, we'll start by creating an object, then we'll do some destructuring:

let wizards = {
  gryffindor: 'Potter',
  slytherin: 'Malfoy',
  hufflepuff: 'Diggory',
  ravenclaw: 'Chang'
};

let {gryffindor: harry} = wizards;
let {slytherin: draco} = wizards;
console.log(harry); // prints 'Potter'
console.log(draco); // prints 'Malfoy'

Here, we have created an object, then created two variables (harry and draco) and assigned values to those variables based on keys in that object (gryffindor and slytherin). You can also do this all in one declaration, like so:

let {hufflepuff: cedric, ravenclaw: cho} = wizards;
console.log(cedric); // prints 'Diggory'
console.log(cho); // prints 'Chang'

Theres another useful shortcut we can take when destructuring objects. Lets look:

let {gryffindor} = wizards;
console.log(gryffindor); // prints 'Potter'

let {slytherin, hufflepuff} = wizards;
console.log(slytherin); // prints 'Malfoy'
console.log(hufflepuff); // prints 'Diggory'

In the above example, I have both referenced the key of an object AND created a variable with the same name as that key, then assigned the value associated with that key to the new variable. In short, if you want to keep the key as the name of the variable, all you have to do is type the key. And you can also do this for multiple variables in one assignment. Theres one more thing to keep in mind when reassigning variables this way: if you arent declaring the variable (using var, let, or const), then you must wrap the entire expression in parentheses. Easy enough:

({gryffindor, slytherin}) = wizards;
console.log(gryffindor); // prints 'Potter'
console.log(slytherin); // prints 'Malfoy'

Conclusion

Although destructuring isn't a game-changing weapon, it can still be a useful tool for you to employ. Use destructuring to write cleaner, more concise code, and to deftly navigate assignment within arrays and objects!

Top comments (1)

Collapse
 
wulymammoth profile image
David

I love destructuring assignment! I wasn't familiar with the ability to skip elements! A few languages have this available, but modern JS takes the cake with the ability to unpack object properties with less typing.

If you ever explore functional languages, it's a very similar idea to "pattern matching" (not in the regular expression sense). In Elixir:

# percent curly braces are the syntax for maps in Elixir (can just think of them as objects in JS)
person = %{name: "david", location: "SF", beverage: "coffee"}
%{name: first_name, location: city} = person # similar to your first object example
> first_name
"david"
> city
"SF"
Enter fullscreen mode Exit fullscreen mode