DEV Community

Cover image for ⚑⚑ a short guide to object destructuring in JS ⚑
Benjamin Mock
Benjamin Mock

Posted on

8 2

⚑⚑ a short guide to object destructuring in JS ⚑

Want to get better at Web Development πŸš€πŸš€πŸš€? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/


Destructuring in JS is used to access object properties in an elegant way.

Let's have a look at a JS object:

const pastry = {
  name: "waffle",
  sweetness: 80,
  ingredients: ["flour", "butter", "eggs"],
  origin: {
    country: "Greece",
    name: "obelios",
    year: 1200,
  }
};

To access its properties we could use the dot notation:

const name = pastry.name;
const sweetness = pastry.sweetness;
const country = pastry.origin.country;

Or with less code, we could use destructuring by specifying the properties, that we want to get.

So instead of

const name = pastry.name;

we can also use

const { name } = pastry;

which looks for the property name inside of the pastry object. It's basically the same as accessing it via pastry.name.

The cool thing is, that you can access multiple properties at once. Let's use the example from above where we accessed name and sweetness.

const { name, sweetness } = pastry;
console.log(name);
console.log(sweetness);

destructuring nested objects

Let's have a look at how to destructure e.g. the country from the origin property.

// const country = pastry.origin.country;
// or

const { origin: { country } } = pastry;
console.log(country); // Greece

You can of course also combine accessing nested and non-nested properties:

const { name, sweetness, origin: { country } } = pastry;
console.log(name);
console.log(sweetness);
console.log(country);

Want to get better at Web Development?
πŸš€πŸš€πŸš€subscribe to the Tutorial Tuesday βœ‰οΈnewsletter

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
lady_ana_developer profile image
Ana β€’

It is funny and interesting at the same time

Collapse
 
vishalraj82 profile image
Vishal Raj β€’

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE