JavaScript destructuring
In JavaScript we work a lot with Objects, especially in React when each component is an Object and we’re passing props which are Objects. We’re often required to unpack the objects to use the variables they contain and JavaScript destructuring is one way we can do this.
Destructuring Objects
Let’s create a simple Object called car
containing two properties for the make
and model
. The traditional way to retrieve these two properties would be to access them using objectname.property
as below.
This object can be destructured into two variables called make
and country
in the following way.
We can also just take the properties that we require from the object and leave the rest.
Destructuring Arrays
It’s not only Objects that we can destructure – it works with Arrays too like this:
There is a difference if we only want to retrieve certain items from the Array because the items in an Array don’t have names like Properties of an Object do. We have to skip any items in the Array we don’t want to destructure by adding extra commas for any item we don’t want.
There are some interesting uses for destructing particularly with Arrays. For instance, if we have a string, we can destructure each character into an Array in the following way.
Destructuring is another feature that is heavily used in React when passing properties between components and handling data, so it’s a useful thing to know.