Array Destructuring in JavaScript

Destructuring is an ECMAScript 6 (ES6/ECMAScript 2015) feature. When it comes to arrays, destructuring is basically a way to unpack values from an array into separate variables. In other words, destructuring is all about breaking a complex data structure (an array in this case) down into a smaller (and therefore simpler) data structure, like a variable.

For arrays, the primary benefit of destructuring is that we can retrieve elements from the array and store them into variables in a very easy way. Let’s start with a very simple array and use destructuring to extract elements from it.

Extracting Elements

let arr = ['Soumadri', 'Sunil', 'John'];

And now, here’s how we would retrieve each element traditionally.

let name1 = arr[0];
let name2 = arr[1];
let name3 = arr[2];
console.log(name1, name2, name3);

Which would give us the following output:

Now, let’s see how we’d do the same thing using destructuring. To destructure an array, we use a ‘[]’ on the left-hand side of the assignment operator. Whenever JavaScript sees this, it will know that it needs to perform destructuring.

And now, using destructuring, we can declare all three variables at the same time. Let’s see how we’ll do it:

let [name1, name2, name3] = arr;

That’s it. And now let’s check the result in the console.