Destructuring
When you need several properties of an object, you often write a line for each of them:
const leo = { name: "Leo", species: "lion", age: 6 };
const name = leo.name;
const age = leo.age;Destructuring does the same in one line:
const leo = { name: "Leo", species: "lion", age: 6 };
const { name, age } = leo;
console.log(`${name} is ${age} years old.`);Leo is 6 years old.On the left of the =, in curly braces, are the properties you want to take out of the object. JavaScript creates a variable for each of them, with the property's name and value. The order in the braces doesn't matter: { age, name } works the same. The object stays as it was, and the properties you don't name, like species here, just don't get a variable.
Arrays can be destructured too, with square brackets. Here the order is what counts: the first variable gets the first element, the second variable the second element, and so on:
const ages = [12, 6, 4, 2];
const [first, second] = ages;
console.log(first, second);12 6This goes well with sorting. Sort a copy of an array and take out the elements at the top:
const [youngest, secondYoungest] = [...animals].sort((a, b) => a.age - b.age);
console.log(youngest.name, secondYoungest.name);Pip GinaTypical mistakes:
- A name in the curly braces that isn't a key of the object.
const { Name } = leo;givesNamethe valueundefined, because the key isname, with a small n. - A variable that already exists. Destructuring creates new variables, so if the program already has a
const name, thenconst { name } = leo;ends withSyntaxError: Identifier 'name' has already been declared. Remove the old line.
Instructions
Replace the two lines that create name and time with one line that takes both out of winner with destructuring. The program prints the same as before: Mia won in 49 seconds.
Below, take the first three runners out of ranking with array destructuring, as gold, silver and bronze. Print their names: Podium: Mia, Liam, Zoe.