Destructuring
The usual way of accessing properties on an object is with dot notation:
That is, someProperty
is a property of an object assigned to someVariable
. Since objects can be nested, you just keep adding dots to reach deeper into the object, eg:
But here’s a simple case of accessing a property one level deep:
Because it can be too wordy to have to write object.property
all the time, you might assign it to a variable:
However if you have many properties you want to pull out, you end up with lines and lines of boring assignments:
An alternative is to use destructuring:
When you destructure, you are essentially pulling out and declaring whichever properties you want from a source object.
You can also use let
when destructuring:
Destructuring is also a great way of using arrays in a more code-readable way. In the below case, we have an array of two values, and we know that the first should be the x and second y. Without destructuring, we’d do the usual thing of assigning values to named variables, so they are more meaningful:
With destructuring, this can be done in one line:
This example can be taken one step further to eliminate point
altogether, by destructuring the function argument directly:
…and if we want to keep simplifying: