What is so special about ES6 Destructuring

Know everything about what it is and how it works in JavaScript

Yogesh Chavan
Dec 10, 2019 · 8 min read
Photo by Fabian Grohs on Unsplash

Today we will see a very popular concept in ES6 known as destructuring. It’s one of the most widely used feature in ES6. In this article we will see how we can apply it in our code and take advantage of this new syntax to write code that is easy to understand and to make the code shorter.

So Let’s get started.

1. Object Destructuring:

Consider, we have following object

const post = {
image: 'http://unknown-site.com/image.jpg',
likes: 200,
comments: 400,
date: '2019–12–20'
};

If we want to get all the values from the object, Using ES5 Code we can write it as

const image = post.image;
const likes = post.likes;
const comments = post.comments;
const date = post.date;

This is too much code and there is repetition of each property in each line

So we can write the same code using ES6 Object destructuring in a single line

const { image, likes, comments, date } = post;

The code above creates local variables with the same name as the properties of the post object.

So it means, For ex. creating a local variable with name image and take the value from post.image.

One thing to note is that, the name used inside curly brackets has to match with the property name

So we cannot do something like this

const { new_image } = post;

This will result in error because there is no new_image property to destructure in the post object.

It’s not necessary, to destructure all the properties from post object. We can only take the properties which we need

const { image } = post;
// The above line is same as
const image = post.image

We can also assign default values to the destructured properties.
Suppose, if we don’t have an image for the post as

const post = {
likes: 200,
comments: 400,
date: '2019–12–20'
};

we can use default parameter syntax to set default image using assignment operator as

const post = {
likes: 200,
comments: 400,
date: '2019–12–20'
};
const {
image = ‘http://unknown-site.com/defaultimage.jpg',
likes,
comments,
date
} = post;
console.log(image); // http://unknown-site.com/defaultimage.jpg
console.log(likes); // 200
console.log(comments); // 400
console.log(date); // 2019–12–20

Obviously, if we have the image property in the post object, that will be used instead of the default value like

const post = {
image: 'http://unknown-site.com/image.jpg',
likes: 200,
comments: 400,
date: '2019–12–20'
};
const {
image = ‘http://unknown-site.com/defaultimage.jpg',
likes,
comments,
date
} = post;
console.log(image); // http://unknown-site.com/image.jpg
console.log(likes); // 200
console.log(comments); // 400
console.log(date); // 2019–12–20

There are situations when we already have another variable with the same name in the current scope as the destructured property so it will create conflict and will result in error. To fix this, we can use the renaming syntax of object destructuring as below

const { date: post_date } = post;
console.log(post_date); // 2019–12–20

Here we are taking the date property and instead of creating local date variable we are renaming it to post_date so if you try to printing the date variable value, you will get error because it does not exist as we have renamed it to post_date now

const { date: post_date } = post;
console.log(post_date); // 2019-12-20
console.log(date); // error: date is not defined

We can also combine the default value and renaming syntax together like

const post = {
likes: 200,
comments: 400
};
const { date: post_date = '2019-12-10'} = post;
console.log(post_date); // 2019-12-10

In the above code, in the highlighted code we are saying, take the date property from post object and rename it to post_date. If the date property does not exist then assign default value of 2019–12–10 to post_date variable.

Suppose, we have a registerUser function which accepts a user object as a parameter

function registerUser(user) {
// David 20 New York david@11gmail.com
console.log(user.name, user.age, user.location, user.email);
}
const user = {
age: 20,
name: 'David',
location: 'New York',
email: 'david@11gmail.com'
};
registerUser(user);

We can use destructuring syntax here to simplify the code

function registerUser({ name, age, location, email}) {
// David 20 New York david@11gmail.com
console.log(name, age, location, email);
}
const user = {
age: 20,
name: 'David',
location: 'New York',
email: 'david@11gmail.com'
};
registerUser(user);

As you can see the function is simplified a lot. We no longer need to refer to user object every time to get the value again in the function. Also the order in which its destructured does not matter and so is the case with which property to destructure

function registerUser({ location, age }) {
console.log(location, age); // New York 20
}
const user = {
age: 20,
name: 'David',
location: 'New York',
email: 'david@11gmail.com'
};
registerUser(user);

In the above code, we are accessing location before age in the function declaration which is fine because while destructuring the property name is used to destructure and not the position of the property.

Now consider, while registering, the name is optional field so we can set it to default value.

function registerUser({ name = 'Unknown', age, location }) {
console.log(name, age, location); // Unknown 20 New York
}
const user = {
age: 20,
location: 'New York',
email: 'david@11gmail.com'
};
registerUser(user);

Now consider, user has already registered with email and we are updating his profile so everything is optional now so we can simplify it as

function updateUser({ 
name = 'Unknown',
age = 0,
location = 'Unknown'
}) {
console.log(name, age, location); // Unknown 0 Unknown
}
updateUser({});

For better readability, we have added each object property on separate line which is a valid syntax and you can also do it, if there are multiple properties on single line just for readability purpose.

But this does not look good, because we need to pass empty object to the updateUser function every time.

We can fix this by setting the default object if we don’t pass it

function updateUser({ 
name = 'Unknown',
age = 0,
location = 'Unknown'
} = {} ) {
console.log(name, age, location); // Unknown 0 Unknown
}
updateUser();

Wow, that’s so cool. Now we can pass only values which are provided by user and others will be set to default values as shown below

function updateUser({ 
name = 'Unknown',
age = 0,
location = 'Unknown'
} = {} ) {
console.log(name, age, location);
}
updateUser({ name: 'David' }); // David 0 Unknown
updateUser({ age: 20 }); // Unknown 20 Unknown
updateUser(); // Unknown 0 Unknown

Now, you can understand the power of destructuring.

2. Array Destructuring:

Array destructuring works the same as object destructuring but instead of using name to identify the property as in object destructuring, we identify it by position in array starting with position zero.

ES5 Code:

const months = ["January", "February"];
console.log(months[0]); // January
console.log(months[1]); // February

ES6 Code:

const months = ["January", "February"];
const [firstMonth, secondMonth] = months;
console.log(firstMonth); // January
console.log(secondMonth); // February

As you can see, the value from the array months with index 0 get assigned to firstMonth variable and index 1 value will be assigned to secondMonth variable.

If we want only the first value we can also do that as

const months = ["January", "February"];
const [firstMonth] = months;
console.log(firstMonth); // January

But what if we want only second month and don’t want to create variable firstMonth if we are not using it. we can skip it as shown below

const months = ["January", "February"];
const [,secondMonth] = months;
console.log(secondMonth); // February

Note, there is comma before the secondMonth variable which will allows us to skip the creation of variable. So if we want to get the 3rd element of the array we can add one more extra comma

const months = ["January", "February", "March"];
const [,,thirdMonth] = months;
console.log(thirdMonth); // March

We can also assign the default value if the value does not exists.

const months = [];
const [ firstMonth = "January" ] = months;
console.log(firstMonth); // January

Suppose you want to swap 2 numbers.

ES5 Code:

let x = 10, y = 20;
let temp;
// Swap the x and y
temp = x;
x = y;
y = temp;
console.log(x, y); // 20 10

ES6 Code:

const [y, x] = [10, 20];
console.log(x, y); // 20 10

We can also use the rest operator which is three dots combined with array destructuring

const months = ["January", "February", "March"];
const [firstMonth, ...restMonths] = months;
console.log(firstMonth); // January
console.log(restMonths); // ["February", "March"]

We can extend this further also

const months = ["January", "February", "March", "April"];
const [firstMonth, secondMonth, ...restMonths] = months;
console.log(firstMonth); // January
console.log(secondMonth); // February
console.log(restMonths); // ["March", "April"]

Now we will look into some complex examples of destructuring

Example 1:

const users = [ 
{
name: 'David',
age: 20
},
{
name: 'Billy',
age: 40
},
];

Now, suppose we want to get the first user object

const [firstUser] = users;
console.log(firstUser); // {name: "David", age: 20}

What if we want to get the name from the first user object?

const [{ name }] = users;
console.log(name); // David

Sounds complex? Let’s break it down

First to get the 1st object of the array, we used the following

const [firstUser] = users;

Now from that object we want name property, so we use object destructuring syntax where the variable name has to match the property name of the object so we destructured it as

const [{ name }] = users;

Example 2:

Now consider we have visitedCountries object

const visitedCountries = {
countries: ["USA", "JAPAN"]
};

How can we get the first country from the list of countries?

const { countries: [ firstCountry ] } = visitedCountries;
console.log(firstCountry); // USA

and how to get the second country ??

const { countries: [ , secondCountry ] } = visitedCountries;
console.log(secondCountry); // JAPAN

Example 3:

Consider, we have a users array. Each array represents the name, country, age

const users = [
["David", "USA", 30],
["Billy", "Japan", 35],
["Mike", "Singapore", 50]
];

How can we convert it to array of objects as shown below ?

const convertedUsers = [
{
"name": "David",
"country": "USA",
"age": 30
},
{
"name": "Billy",
"country": "Japan",
"age": 35
},
{
"name": "Mike",
"country": "Singapore",
"age": 50
}
]

We can use the map method and array destructuring here

const convertedUsers = users.map(function([name, country, age]) {
return { name: name, country: country, age: age };
});
console.log(convertedUsers);
/* output[
{
"name": "David",
"country": "USA",
"age": 30
},
{
"name": "Billy",
"country": "Japan",
"age": 35
},
{
"name": "Mike",
"country": "Singapore",
"age": 50
}
]
*/

As you can see from the above code

return { name: name, country: country, age: age };

the key and value are same, so we can further simply it using ES6 Object Shorthand syntax as

const convertedUsers = users.map(function([name, country, age]) {
return { name, country, age };
});

This is still taking three lines of code so we can further simplify it using arrow function as

users.map(([name, country, age]) => ({ name, country, age }));

Here we are implicitly returning the object { name, country, age } by adding it inside the round brackets ().

The output is same as above but its easy to understand and will save from typing some extra characters.

That’s it for today. Hope you learned something new today.

Want to become an expert in Javascript? Download your free ebook HERE

JavaScript in Plain English

Learn the web's most important programming language.

Yogesh Chavan

Written by

Full Stack Developer | Javascript | React | Nodejs. Want to become an expert in Javascript? Get your FREE Ebook HERE: http://bit.ly/free_js_ebook

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade