About 25-30 minutes
Destructuring syntax is shorthand that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
It also works in the other direction to create values.
Given this car
object we can destructure its properties into variables.
const car = {
type: 'Tesla',
color: 'White'
};
const { type, color } = car;
type // => 'Tesla'
color // => 'White'
Split a String into a 2-length array.
const str = 'Michelle+TaLea';
const [p1, p2] = str.split('+');
p1; // => 'Michelle'
p2; // => 'TaLea'
This may be the most powerful and useful of them all. It can be used on the right-hand side of assignment as well.
Using the same syntax as the last example, we can now pass in an object as an argument and just destructure the properties we need off of it right in the parameter list.
function reportAge({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
const child = {
name: 'Suzie',
age: 5
};
reportAge(child);
reportAge({ name: 'Michelle Obama', age: 56 });
function reportAge(person) {
const name = person.name;
const age = person.age;
console.log(`${name} is ${age} years old.`);
}
Rewrite the following code using destructuring to reduce repetition.
const request = {
body: {
username: 'hello',
password: '1234'
}
};
const username = request.body.username;
const password = request.body.password;
console.log(username);
console.log(password);
What is the output? Why does that happen?
(Hint: write the same code without destructuring that produces the same output)