Object Destructuring in JavaScript

Object destructuring is a helpful enhancement made to JavaScript syntax as part of ES2015.

Let's say we have a social media application with user objects containing several properties.


cont user = {
first: "Marlon",
last: "Brando",
email: "marlon@gmail.com",
followers: 578226,
birthYear: "1924",
};

We want to write a function called makeUsername that generates a simple username based on these properties. For example, we want to combine the first and last names and add the last two digits of the birth year, leaving the output as 'MarlonBrando24'.

We'll need to extract the first name, last name, and birth year from the user object to achieve this.

In the past, the only way to do this within JavaScript was with a repetitive pattern where each variable matches the name of one of the properties.


const first = user.first;
const last = user.last;
const birthYear = user.birthYear;

Using Object Destructuring

Instead of writing multiple lines to extract properties from the user object, we can use object destructuring to do it more concisely:


const { first, last, followers, birthYear } = user;

This single line of code does the same thing as the three lines above. It extracts the first, last, followers, and birthYear properties from the user object and assigns them to corresponding variables.

We use curly braces on the left side of the equal sign and set the right side equal to our user object. Inside the curly braces, we list the different properties we're interested in creating variables for.

You can execute this code in the console of your devtools to verify the variables:


first;
last;
followers;
birthYear;

Important: The names inside the curly braces must match the property names in the object. If we try to destructure a property that doesn't exist in the object, JavaScript will set the new variable to undefined.


const { middleName } = user;
// middleName is undefined!

Now, we can use these variables to create our simple makeUsername function:


function makeUsername({first, last, birthYear}) {
return first + last + birthYear.slice(-2);
}

This function takes a user object, destructures it to get the first name, last name, and the two last digits of the birth year, and then generate the username by concatenating these values. And that's how object destructuring can help us simplify our code and make it more readable.

The next time you need to extract multiple properties from an object in JavaScript, try object destructuring to simplify your code and make it more readable.

Transcript

00:00 In this video, we'll cover object destructuring, a really useful enhancement that was made to JavaScript syntax. A couple of years ago at this point, it was part of ES2015, and it's something that I use day-to-day when I'm writing JavaScript. So here I have an object literal representing a single user for a website,

00:18 let's say a social media application. It has a bunch of properties, first name, Marlon, last name, Brando, e-mail, a number of followers, and a birth year. I want to write a function called make username. It's going to be a very simple username that it generates based on a user.

00:35 Basically, what I wanted to do is take the first name from any object like Marlon, take the last name, smoosh it together so we have Marlon Brando, and then take the last two digits of the birth year, in this case, 24. This will be your automatically generated username. It's not guaranteed to be unique,

00:53 it's just a simple little demonstration function. So to do this, I'm going to need to extract the first name, I'll need to extract the last name, and the birth year. For a while, we really only had one way of doing this in JavaScript. We would do something like this, we'd make a variable, I'll do it in the console over here,

01:11 const firstName, I'll just call it first, equals user.first, and then that would get me the firstName variable, or first, and then I could do the same thing, const last equals user.last,

01:26 and const birthYear equals user.birthYear. It gets quite repetitive, not to mention that it takes three lines to do it, but each line follows the same pattern. We have some variable that is matching the name of some property. I'm just trying to extract a value out of the object,

01:45 so I can then use them. So with destructuring, we have a syntax that we can use to extract values from an object by calling out their names, and creating new variables using those names. It looks like this. I'll just do it right here first, and then we'll move to my function.

02:02 We use curly braces on the left side of the equal sign. I'm going to set the right side equal to our user object. Then inside of the curly braces, I can list the different properties I'm interested in creating variables for. So I'll do first, last. Why don't we do followers while we're here,

02:20 and birthYear. Now, these names must match some name that's already in here. In this case, first matches first, last, last, followers, followers, birthYear, and birthYear. This will make me four separate variables in a single line, and each variable will be set to

02:39 the corresponding property from the user object. So first will be set to user.first, last is set to user.last, and so on. So let me refresh the page, and I'll show you that we now have a first variable set to Marlon. We have a last variable set to Brando. We have a followers variable set to that number,

02:58 and we have a birthYear variable. Now, we do not have an e-mail variable. I did not destructure the e-mail property into its own variable. Additionally, if I did not match these correctly, let's say just called this year, take a look at what happens. I still get a first variable and a last variable.

03:17 But if I look at year, it's just set to undefined. JavaScript could not find a year property in this user object. So in this case, I destructured four different variables, although one of them is set to undefined. So let's go back to birthYear, which is the name in the actual object. Again, they have to match.

03:36 One thing that we do a lot with destructuring is actually destructure an object as it comes into a function as an argument. So if I write this makeUser function, I'm going to extract the different variables out, the different properties from my user object. So first, last, I don't really need the followers property.

03:53 Remember, my goal is to make a little string that I return that has the first name, concatenated with the last name, concatenated with the last two digits of birthYear. So I can extract those three things, and then I can just return something like first plus last plus,

04:11 and I'll just start with the whole birthYear. This should work if I call makeUserName now, makeUserName, and I pass through the Marlon Brando object called user, this is what it returns to me, and that's great. But I don't need anything else from that object in this function. I just am interested in first, last, and birthYear.

04:30 So what a lot of people will do is destructure in the function parameter list right here, and that looks like this. If we put our curly braces inside of the parentheses of a function definition, we can destructure, and in this case, we'll have access to three different variables in this function,

04:48 first, last, and birthYear. It should still work just fine if I rerun that line. It does, Marlon Brando 1924. So that's a really common thing that we'll do. Now, I did say I only wanted to use the last two numbers in birthYear,

05:04 so I'm just going to tweak this slightly and slice negative two, so the last two digits, and now we get Marlon Brando 24. Then if I had another user, how about this user2 object, Greta Garbo, born in 1905. If I now try and call this function with user2,

05:23 it will destructure first, last, and birthYear as the values from that object are passed into the function. Well, it will make three separate variables that I can use within the function and we get Greta Garbo 05. So just a simple example of object destructuring.

05:39 We can do it on our own just when declaring variables ourself or defining variables, or we can do it inside of a function parameter list,

05:47 which makes our life a lot easier and cleans up the code significantly.

More Tips