DEV Community

loading...

Object Destructuring Javascript ES6

alhiane profile image Alhiane Lahcen ・1 min read

// Example 1
// bind variables to different "car1" object properties

const car1 = {
  name: "fiat",
  model: 500,
  weight: 850,
  color: "red"
};


const { name, color, weight } = car1;

Enter fullscreen mode Exit fullscreen mode

// Example 2
// destruct an object property from a variable
// Rename a variable
// set a value to a variable

const car2 = {
  brand: "fiat",
  model: 500,
  weight: 850,
  colors: {
    red: true,
    green: false
  }
};
Enter fullscreen mode Exit fullscreen mode

// Use ":" sign" to change the name of the variable
// Use the "=" sign to assign a value to a variable

const {
  colors: { red: redColor, white: whiteColor = false, brown = "true" }
} = car2;
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
aminnairi profile image
Amin

Hi there!

Did you know that you can format your JavaScript code in Markdown? Check out the documentation here for more informations.

I think that a better styling is more appealing to the eyes and can really make your article stand out.

Thank you!

Collapse
alhiane profile image
Alhiane Lahcen Author

this way it will be better
thank you!