How to destructure property to a different name?

Learn JS: Destructuring Lesson 4.

(I'm assuming you know how to destructure object properties)

We're going to work with the same object as in the previous lessons:

const ages = {
robot: 23,
person: 33,
dog: 1

What I haven't talked about yet are situations when you want to bind the property to a variable with a different name. Maybe it will improve readability or its name clashes with another variable that you don't want to change. It's something you need to do from time to time.

Let's start with the example in the old syntax:

const Trurl = ages.robot;

Changing the name is easy with the . (dot notation). You don't need to use destructuring all the time. Dot notation is still used a lot in new code thanks to its simplicity so remember about it.

What if you already use destructuring a lot and want to change the name of one of the existing properties?

const { robot, person, dog } = ages;

The first option is to move out a given variable from destructuring expression.

const { person, dog } = ages;
const Trurl = ages.robot;

The problem is that your diff when submitting a PR is unnecessarily big, not to mention that it's now harder to read. Fortunately, you don't have to do that if you want to keep the consistency of destructuring. You can use : to indicate a new variable name for the destructuring property:

const { robot: Trurl /* New name! */ } = ages;
// robot is not defined
// Trurl -> 23

Let's see that in the original example:

const { robot: Trurl, person, dog } = ages;

It might be a good idea to reformat your code into multiple lines to make it easier to see.

const { 
robot: Trurl,
} = ages;

The benefit of a syntax like that is that you can assign multiple names at the same time:

const { 
robot: Trurl,
person: Lem,
dog: westie
} = ages;

You might be confused about how we can use custom name and default value at the same time? The good news is that you can. The default value is applied as the last thing just in case your value is undefined. To make it work just remember to use default value at the end:

const { 
robot: Trurl = 333,
ghost: hauntedHouseGhost = 12
} = ages;
// Trurl -> 23 (as it gets value from ages.robot)
// hauntedHouseGhost -> 12

Please let me know if you have any questions.

If you like this newsletter, then please share it with your friends:

Next lesson

(Previous lesson)

Share on Hacker News
Share on LinkedIn

← Home

Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.