DEV Community

Cover image for Objects De-structuring...
Colby Cardell
Colby Cardell

Posted on

Objects De-structuring...

To start, Object De-structuring is a way you can basically extract values from a Object and put them inside individual variables.

Example:

const car = {
  make: 'Honda',
  model: 'Civic'
};

let { make, model } = car;

console.log(make);
console.log(model);

//Honda
//Civic

Enter fullscreen mode Exit fullscreen mode

We define an Object called car with a few properties, called make & model. So we can extract the properties from this Object and set them to individual variables using { } this syntax right here.

Basically, we are just defining 2 new variables make & model and setting them to the values of the property names inside of the Object.

You Can Also Set Default Values:

const car = {
  make: 'Honda',
  model: 'Civic'
};

let { make, model, year = 'Unknown' } = car;

console.log(make);
console.log(model);
console.log(year);

//Honda
//Civic
//Unknown

Enter fullscreen mode Exit fullscreen mode

So.. The car Object does not contain the year property but we can still set a year variable and set it to Unknown.
But if we define a year property in the Object it will override the Default Value by the actual car property.

We Can Do Something Very Similar Using Functions:

const car = {
  make: 'Honda',
  model: 'Civic'
};

function carDataSheet({ make, model }) {
  console.log(`The Car is a ${make} ${model}! `);
}

  carDataSheet(car);

//The Car is a Honda Civic!

Enter fullscreen mode Exit fullscreen mode

I feel lost at function sometimes.. But, its actually really simple. So with carDataSheet(car) we are passing in the Object, and have set a parameter ({make,model}). And its really doing the same thing as above..
So we are extracting the make & model property of this Object & setting it to the variables inside of the function. That is basically Object De-structuring in a nut shell!!

Top comments (0)