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.
let car = {
make: 'Ferrari',
model: 'Enzo'
}
console.log(car.make);
console.log(car.model);
Ferrari
Enzo
This object can be destructured into two variables called make
and country
in the following way.
let car = {
make: 'Ferrari',
model: 'Enzo'
}
let {make, country} = car;
console.log(make);
console.log(model);
Ferrari
Enzo
We can also just take the properties that we require from the object and leave the rest.
let car = {
make: 'Ferrari',
model: 'Enzo',
country: 'Italy',
colour: 'Red'
}
let {make, colour} = car;
console.log(make);
console.log(colour);
Ferrari
Red
Destructuring Arrays
It’s not only Objects that we can destructure – it works with Arrays too like this:
let car = ['Ferrari', 'Enzo', 'Italy', 'Red'];
let [make, model, country, colour] = car;
console.log(make);
console.log(model);
console.log(country);
console.log(colour);
Ferrari
Enzo
Italy
Red
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.
let car = ['Ferrari', 'Enzo', 'Italy', 'Red'];
let [make, , , colour] = car;
console.log(make);
console.log(colour);
Ferrari
Red
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.
let [a, b, c] = "abc";
console.log(a);
console.log(b);
console.log(c);
a
b
c
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.