ES6 came with some awesome features that make complex coding techniques easier to implement. One of these features is
Array Destructuring, which we will be covering in this article.
Practice along : )
Destructuring is the act of ‘Destruction’.
Destruction is the process of destroying (or reducing) something to its smallest pieces.
The reduction may only be to
1 level or to the least level (depending on the depth of the array and how far you want to destructure it).
Let’s look at an example array:
let awesomeArray = ["educative", "dot", "io"];
If we were to access the contents of this area without destructuring, we would have to use this method:
console.log(awesomeArray); // Expected output: io let edu = awesomeArray; console.log(edu); // Expected output: educative
With array destructuring implemented, we would have:
let [ edu, var1,var2 ] = awesomeArray; console.log(edu, var1, var2); // Expected output: // educative // dot // io
Note that the spaces after the opening bracket and before the closing bracket do not mean anything. It’s for readability purposes only.
edu gets the first object of the array while var2 gets the second object.
What if we want to skip objects, say, in a very long array?
Let’s take a look at another example:
Note that a comma has to end the ‘awesomeLanguage’ variable while the remaining commas represent skipped objects.
let deepArr = [ "welcome", "to", [ "class", "school", "office" ] ] let [ ,,locations ] = deepArr; let [ first,,third ] = locations; console.log(first, third); // Expected output // class // office
By now, you should understand the process of destructuring with specified levels right?
let bigArr = ["name", 4,5,6]
From this array, we might need just the name and we might want the numbers to have their own array. We would achieve this in combination with the
let [ important, ...secondArr ] = bigArr; console.log(imporant, secondArr) // Expected Output: // name // [4,5,6]
With array destructuring, you can create your own arrays from your variables and also swap them. Here’s how:
let first = "educative"; let second = "io"; [first, second] = [second, first]; console.log(first, second); // Expected output // io // educative
By now, you should see how easy it is to access data from small and big arrays by reducing them through Array Destructuring.
There’s another destructuring technique,
Object destructuring, which implements this same concept.
There’ll be a future article on that, so stay tuned : )
View all Courses