How to use destructuring assignment to access object property?

Learn JS: Destructuring Lesson 1.

Let's start with a sample object:

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

We can access its properties with a . (dot notation)

const robot = ages.robot;
const person = ages.person;
const dog = ages.dog;

It works in all versions of JS, and you can use that whenever you're not sure if new language features are available. Starting from ES6, we can access the object properties with a little less typing.

const { robot } = ages;
const { person } = ages;
const { dog } = ages;

Hey! All those { and } look like more typing not less!

As you noticed, it's not that useful if you're only destructuring one property at a time. Fortunately, you can join all of those declarations into one expression.

const { robot, person, dog } = ages;

Accessing multiple properties at the same time is when destructuring shines. You have to get used to it but having less code is worth the effort.

I want to dig deeper into destructuring in the next few posts so until next time!

Next 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.