Skip to content

Destructuring

The usual way of accessing properties on an object is with dot notation:

const someVariable = {
someProperty: `foo`
}
someVariable.someProperty; // `foo`

That is, someProperty is a property of an object assigned to someVariable. Since objects can be nested, you just keep adding dots to reach deeper into the object, eg:

const person = {
address: {
street: {
number: 28
name: `West`
},
suburb: `Brisbane`,
state: `QLD`,
country: `🇦🇺`
},
name: `Bob Jane`
}
person.address.street.number; // 28

But here’s a simple case of accessing a property one level deep:

const settings = Object.freeze({ colour: `red`, size: 20 });
const something = () => {
console.log(settings.colour);
}

Because it can be too wordy to have to write object.property all the time, you might assign it to a variable:

const something = () => {
const colour = settings.colour;
console.log(colour);
}

However if you have many properties you want to pull out, you end up with lines and lines of boring assignments:

const something = () => {
const colour = setings.colour;
const size = settings.size;
const hope = settings.hope;
const dreams = settings.dreams;
const diminishing = settings.diminishing;
...
}

An alternative is to use destructuring:

const something = () => {
const { colour, size } = settings;
console.log(`colour: ${colour}`);
// Same as
// const colour = settings.colour
// const size = settings.size
}

When you destructure, you are essentially pulling out and declaring whichever properties you want from a source object.

You can also use let when destructuring:

let { colour } = settings;

Destructuring is also a great way of using arrays in a more code-readable way. In the below case, we have an array of two values, and we know that the first should be the x and second y. Without destructuring, we’d do the usual thing of assigning values to named variables, so they are more meaningful:

const something = (point) => {
const x = point[0];
const y = point[1];
return x*y;
}
something([10, 20]);

With destructuring, this can be done in one line:

const something = (point) => {
const [x, y] = point;
return x*y;
}
something([10, 20]);

This example can be taken one step further to eliminate point altogether, by destructuring the function argument directly:

const something = ([x,y]) => {
return x*y;
}
something([10, 20]); // 300

…and if we want to keep simplifying:

const something = ([x,y]) => x*y
something([10,20]); // 300