Destructuring assignment allows us to give the properties of an array or an object to variables using syntax that looks similar to that of an array or object.
Without destructuring assignment we would usually grab the first three elements of an array like so:
With destructuring assignment, everything is a lot more concise and readable.
Array vs Object Destructuring
Above I showed an example of array destructuring but we can also destructure objects.
Both of these may look closely related in features but there are some differences to note. Object destructuring relies on the name of the variable to match that of the key in the object.
If we assign a variable name and it has no match to an object’s key it will return undefined.
Contrarily, it is possible to assign a different variable name from that of the key.
Array destructuring relies on the index of array elements to get the value(s).
In our example above, the variable ‘two’ is at index 0 of the array. In that array the index 0 holds the number 5. Even though the assigned variable name does not determine the value that is outputted when destructuring arrays we do however want to be precise in our naming choices to make our code more readable.
To skip over items in the array being destructured we can use the
, we omitted “Miami Heat” and “Los Angeles Lakers” from our array.
Additional features to consider
In destructuring an array we can nest patterns as deep as we would like.
We can get all trailing items in an array using the ‘rest’ pattern:
There is a helpful and syntactical shortcut for when the property and variable names are the same:
Similarly to nesting in array destructure we can do the same on object destructuring.
Destructuring works great if you want to access object properties and array items. On top of the basic usage, array destructuring is convenient to swap variables, access array items, & perform some immutable operations.