Curriculum
Course: React
Login

Curriculum

React

Text lesson

ES6 Destructuring

Destructuring

To illustrate destructuring, think of making a sandwich: you only take out the items you need from the refrigerator, not everything. Similarly, destructuring allows you to extract only the necessary items from an array or object, making it easy to work with just what you need.

Destructing Arrays

Here’s the traditional method of assigning array items to variables:

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 modern approach to assigning array items to variables:

Example

With destructuring:

const vehicles = ['mustang', 'f-150', 'expedition'];

const
[car, truck, suv] = vehicles;
When destructuring arrays, the order in which variables are declared is crucial.

To select only the car and SUV, you can omit 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 traditional method of using 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 the modern approach to using 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 + '.';
}
Note that the order of object properties does not need to be specified.

We can destructure deeply nested objects by first referencing the nested object, then using a colon and curly braces to destructure the required items from that nested object.

Example

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 + '.';
}