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

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more β†’

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 β€’

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more