ES6 Destructuring
Destructuring
To demonstrate destructuring, we will create a sandwich. Do you get everything out of the fridge to create your sandwich? No, you only take out the ingredients you want to utilize on your sandwich.
Destructuring is exactly the same. We may be dealing with an array or object, but only a subset of its contents is required.
Destructuring makes it easy to extract only what is required.
Destructing Arrays
Here’s the old method for allocating array items to a variable:
Example
Before:
const vehicles = ['mustang', 'f-150', 'expedition'];
// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];
Here’s the new method for allocating array items to a variable:
Example
With destructuring:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
When destructuring arrays, the order in which variables are declared matters.
If we only want the car and the SUV, we can simply leave out the truck while keeping the comma:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car,, suv] = vehicles;
Destructuring is useful when a function returns an array.
Example
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
return [add, subtract, multiply, divide];
}
const [add, subtract, multiply, divide] = calculate(4, 7);
Destructuring Objects
Here’s the old method for utilizing an object within a function:
Example
Before:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';
}
Here’s a new way to use an object within a function:
Example
With destructuring:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}
It’s worth noting that the object properties don’t have to be specified in any certain order.
We can also destructure deeply nested objects by referencing the nested object and then using a colon and curly brackets to destructure the necessary pieces from the nested object:
the items needed from the nested object:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
}
}
myVehicle(vehicleOne)
function myVehicle({ model, registration: { state } }) {
const message = 'My ' + model + ' is registered in ' + state + '.';
}