Object & Array Destructuring
Modern JavaScript Series

I'm a data analyst, currently living in Copenhagen.
Destructuring in JavaScript
ES6 introduced the new destructing assignment feature, which makes it easy to destructure objects and arrays into variables.
Object destructuring
Let's take object destructuring:
const user = {
firstName: "Christian",
lastName: "Holm",
age: 41
}
Before ES6 we would have to get the properties out of the object manually, by writing a new variable assignment for each property we wanted:
var firstName = user.firstName; // "Christian"
var lastName = user.lastName; // "Holm"
var age = user.age; // 41
But with modern JavaScript we can use object destructuring:
const { firstName, lastName, age } = user;
console.log(firstName); // "Christian",
console.log(lastName); // "Holm",
console.log(age); // 41
The above code example creates the same three variables with data from the object.
If we only need firstname and lastname, we can specify just those two variables:
const { firstName, lastName } = user;
Alias
We can also create variables with different names:
const { firstName: name, lastName: last } = user;
console.log(name); // "Christian"
console.log(last); // "Holm"
Default value
You can set a default value in case the property doesn't exist in the object:
const { firstName, lastName, age, country = Denmark } = user;
console.log(firstName); // "Christian",
console.log(lastName); // "Holm",
console.log(age); // 41
console.log(country); // Denmark
Nested objects
You can destructure the properties of a nested object into individual variables:
// Object:
const admin = {
isAdmin: true,
name: {
firstName: "Christian",
lastName: "Holm",
}
}
// Destructuing the nested name property:
const {
name: {
firstName,
lastName
}
} = admin;
console.log(firstName); // "John"
console.log(lastName); // "Smith"
Array destructuring
Arrays can also be destructured:
const users = ["Mike", "John", "Christian"];
const [a, b, c] = users;
console.log(a); // "Mike"
console.log(b); // "John"
console.log(c); // "Christian"
Rest syntax
If you only need some of the array values you can split them up like this:
const users = ["Mike", "John", "Christian", "Susan", "Joe"];
const [first, second, ...rest] = users;
console.log(first); // "Mike"
console.log(second); // "John"
console.log(rest); // ["Christian", "Susan", "Joe"]
Skipping values
You can also skip values with a comma:
const users = ["Mike", "John", "Christian"];
const [first, ,third] = users;
console.log(first); // "Mike"
console.log(third); // "Christian"
Swapping variables
There’s a trick for swapping the values of two or more variables using destructuring:
let a = 10;
let b = 20;
[a, b] = [b, a]
console.log(a); // 20
console.log(b); // 10
Summary
That's it for this blog post. Hopefully you can see how and why destructuring is a handy new feature in modern JavaScript. It works on both objects and arrays and has a wide, ahem, array of possibilities...

