Destructured Assignment
Thu Jul 21 2022 18:43:15 GMT+0000 (Coordinated Universal Time)
Saved by
@cruz
#javascript
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
const { residence } = vampire;
console.log(residence); // Prints 'Transylvania'
//Look back at the vampire object’s properties in the first code example. Then, in the example above, we declare a new variable residence that extracts the value of the residence property of vampire. When we log the value of residence to the console, 'Transylvania' is printed.
//We can even use destructured assignment to grab nested properties of an object:
const { day } = vampire.preferences;
console.log(day); // Prints 'stay inside'
const robot = {
model: '1E78V2',
energyLevel: 100,
functionality: {
beep() {
console.log('Beep Boop');
},
fireLaser() {
console.log('Pew Pew');
},
}
};
const { functionality } = robot;
functionality.beep();
content_copyCOPY
Comments