EXERCISE
1Destructuring lets you extract properties from an object into separate variables with a single, clean line of code.
Destructuring pulls values out of an object into separate variables in one statement. It replaces a run of lines that each repeat a name twice.
const user = { name: "Sara", age: 28, city: "Dubai" };
const name = user.name;
const age = user.age;
const city = user.city;
Three lines that each say the same thing on both sides of the equals. Repeating a name is exactly the sort of thing that drifts when someone renames a property and misses one.
const { name, age, city } = user;
console.log(name); // "Sara"
console.log(age); // 28
Read the braces on the left as a shape rather than as an object being built. It says: from user, take the properties called name, age and city, and bind each to a variable of the same name. Nothing is constructed and user is not modified.
The matching is by name, not by order:
const { city, name } = user;
console.log(city, name); // "Dubai" "Sara"
Rearranging changes nothing. Asking for a property that does not exist gives undefined rather than an error, exactly as a normal property read would:
const { email } = user;
console.log(email); // undefined
A default covers the missing case:
const { country = "unknown" } = user;
console.log(country); // "unknown"
The default applies only when the property is undefined. A property holding null, 0 or "" is present, so the default does not fire.
Renaming, for when the property name is not the variable name you want:
const { name: userName, city: userCity } = user;
console.log(userName); // "Sara"
The colon reads backwards from an object literal, which catches people: the property is on the left and the new variable name is on the right.
Nested objects use the same shape, one level deeper:
const student = { name: "Ali", address: { city: "London" } };
const { address: { city } } = student;
console.log(city); // "London"
console.log(address); // ReferenceError: address is not defined
That last line is worth knowing. Writing address: { city } uses address as a path, not as a variable, so only city is created.