ES-2015 offers a new and faster way to extract object properties.
MDN definition : The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
The old way
const hero = { name: "Oli", age: "69" };
const name = hero.name;
const age = hero.age;
console.log(`Name : ${name}, Age : ${age}`); // Name : Oli, Age : 69
The fancy way
const hero = { name: "Oli", age: "69" };
const { name, age } = hero;
console.log(`Name : ${name}, Age : ${age}`); // Name : Oli, Age : 69
A special case : nested properties
const hero = {
name: "Oli",
age: 69,
address: {
city: "Montreal",
},
};
const {
address: { city },
} = hero;
console.log(city); // Montreal
Other useful common cases
Outside of the binding of properties, the destructuring synthax can help with the following cases :
Looping through an array of object
const people = [{ name: "Oli" }, { name: "Seb" }];
for (const { name } of people) {
console.log(name); //Oli //Seb
}
Function parameters
const people = [{ name: "Oli" }, { name: "Seb" }];
const names = people.map(({ name }) => {
return name;
});
console.log(names); //["Oli","Seb"]
For reference, pre ES-2015 you would have written the following:
const people = [{ name: "Oli" }, { name: "Seb" }];
const names = people.map((value) => {
return value.name;
});
console.log(names); //["Oli","Seb"]
And pre arrow functions the following atrocious code :
const people = [{ name: "Oli" }, { name: "Seb" }];
const names = people.map(function (value) {
return value.name;
});
console.log(names); //["Oli","Seb"]
Ahhhh sweet sweet javascript...