Destructure & Rename
const {
foo: myFoo,
loading: isLoading,
} = myData;
Here, the shape of myData
will contain a key foo
and another key loading
.
In the destructure & rename syntax above, Here, we are telling Javascript to peek inside myData
and pull out the values associated with the keys foo
and loading
and assign them into new variables called myFoo
and isLoading
.
We both destructure foo
and loading
out of myData
and also rename foo to myFoo
(and loading to isLoading
.)
That means that there will be local constants called myFoo
and isLoading
(not foo and loading).
Do not confuse the colons with Typescript-type declarations. If you see colons inside a destructuring syntax, it’s not a type definition. Instead, it is destructuring and renaming.
It turns out that what I’ve called here “destructure & rename” is in fact the less-common default. That is, the official name of behavior is “destructure” (with the name of the key coming from the object on the left and the new variable name on the right), but in most codebases you actually see more often the use of the shorthand destructuring, also known as “object-property shorthand.”
Shorthand Destructuring
const { foo, loading } = myData;
The myData
contains at least two keys: foo and loading. Here, we are telling Javascript to peek inside myData
and pull out the values associated with the keys foo
and loading
. Those values then become assigned to two local constants called foo
and loading
.
Remember, the shorthand is in fact more common than the long-form above, so it’s easy to learn JS fundamentals by learning only the shorthand and not realizing the longer form destructure & rename exists as explained above.