DEV Community

Cover image for Array Destructuring with ES6
Todd Carlson
Todd Carlson

Posted on

Array Destructuring with ES6

One of my favorite side effects of tech blogging, aside from hopefully writing content that other people find useful, is that it helps me to solidify concepts. This week I am focusing on array destructuring with ES6. You can also use destructuring with Objects, but I am going to save that for a future post.

So what exactly is array destructuring? In a nutshell, array destructuring is taking the individual elements inside of an array, and assigning them to individual variables. So, a basic example might look like this:

let letters = ["a", "b", "c", "d", "e"];
let [one, two] = letters;

console.log(one); // "a"
console.log(two); // "b"

Here we have declared a variable, letters, and assigned its value to an array of strings containing the first five letters of the alphabet. Next we have declared another variable, which is an array containing the variables one and two. We then set those values equal to variable letters, whose value is our array of strings. What this does is allow us to set the variables one, and two equal to the first two elements in our letters array, which we have verified with our two console.log() statements. Keep in mind that in JavaScript we are not allowed to use integers as variable names, so this code would have thrown a syntax error:

let letters = ["a", "b", "c", "d", "e"];
let [1, 2] = letters;

console.log(one); // "a"
console.log(two); // "b"

Another powerful feature of array destructuring is the ability to use Rest syntax. If we take our previous code example and add another variable called three preceded by Rest syntax, which looks like this '...' we get the following result:

let letters = ["a", "b", "c", "d", "e"];
let [one, two, ...three] = letters;

console.log(one); // "a"
console.log(two); // "b"
console.log(three) // ["c", "d", "e"]

Using Rest syntax allows us to take the values that come after one, and two and spread, or copy, those values into a new array stored in the variable three.

Array destructuring is also useful if you want to swap out the values of variables:

let a = "cat"; 
let b = "dog";

[a, b] = [b, a];

console.log(a); // "dog"
console.log(b); // "cat"

Lastly, you can also use destructuring with functions that return arrays of data:

const retArray = () => {
    return ["a", "b", "c", "d", "e"];
}

let [one, two] = retArray();

console.log(one); // "a"
console.log(two); // "b"

As you can see, array destructuring is a powerful feature of ES6. It is especially useful when working with JavaScript frameworks like React and Vue. Stay tuned for my next post where I will explain how to use destructuring with JavaScript Objects.

Until then,
Happy Coding!

Top comments (0)