Member-only story
Why I Find JavaScript’s Destructuring So Useful
Array and object destructuring
Let’s take a look at some of the best features of ES6: object destructuring, array destructuring, and the spread operator. If you want to develop using front-end frameworks such as React — and even if you don’t— they’re incredibly useful for making your code much cleaner and more manageable.
Array Destructuring
Destructuring is the idea of taking an object or an array and converting it into smaller objects, elements, or variables. So let’s take a look at a simple example:
We want to get the very first two elements in that array. Usually, if you’re going to get the first element, you would do something like this. But it’s kind of clunky and there’s a much easier way to do this by using destructuring.
Example:
You take the element you wish to destructure and put that on the right side of the =
sign. Essentially, you’re saying, “Destructure this alphabet array.”
Since we have an array, we put our parentheses over here and our array brackets around the elements that we want to supply, so we have our variable names a
and b
that we want to get out of this array. And then the position of these elements is where they’re going to get pulled out. Hence, A
is the first element inside this array, so it’s going to get the first element. B
is the second element, which is going to get the second element here, and so on.
But what if we wanted to skip B
, for example? What if we only wanted A
and C
? Then, this will miss the second element:
//Destructring Array and skiping element
const [a, ,c] = alphabetsconsole.log(a)
console.log(c)