Unpack arrays, objects & assign them to a distinct variable.
It allows us to write clean & readable code.
In JS, we can destructure
Arrays
Objects
# Destructuring arrays
Arrays - list of different data types, which are ordered by their index.
During destructuring each variable should match with index of desired item in array.
Example for accessing small arrays:
Destructuring
Destructuring & skipping an item: ,
If we are not interested in destructuring an item we can leave it empty with a single , at that specific index.
**Destructuring the rest: …
To get the rest of an array, we use the spread operator ... to get the rest of the array during destructuring.
Destructuring Nested Array
# Use cases: Arrays
When working with arrays we can use array destructuring - when looping though arrays
Destructuring during loop through array
# Destructuring Objects
An object literal consists of key & value pairs.
We already know on how to access objects & their values.
Here is a simple example:
Access the objects values
Access value using destructuring
When we use destructuring, the name of the variable should be exactly the same as the key/property of the object.
Destructuring Nested Objects
Here we destructure step by step
But we also can destructure it in one step
# Spread/Rest Operator
For example, if we have an existing object, and we do just want to change one property in this object, we can change this one property as follows:
The same is there for arrays.
In this example, let’s say we have an array filled up with some names. We want to add another name in another array.