javascript · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
unpacks values, and copies them.
Destructuring pulls values out into variables in one line. const { name, age } = pet; makes two variables, each holding the value under the key with the same name. For arrays, const [first, second] = queue; unpacks by position instead.
The spread operator, three dots, pours one array or object into another. [...snacks, "crisps"] makes a new array with every snack plus crisps. { ...pet, age: 4 } makes a new object with every key from pet, then a new age.
Spread makes new copies, so the original stays exactly as it was.
const pet = { name: "Rex", age: 3 };
const { name, age } = pet;
console.log(name, age);
const older = { ...pet, age: 4 };
const snacks = ["apple", "nuts"];
const more = [...snacks, "crisps"];
console.log(older, pet);
console.log(more, snacks.length); When spread copies an object, a key written after the dots replaces the copied one.
guess first
Upsizing an order. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const order = { food: "pizza", drink: "lemonade", price: 9 };
const { food, price } = order;
const bigger = { ...order, price: price + 3 };
console.log(food, bigger.price, order.price);
your turn
Your turn. Grow a playlist without touching the old one.
Spread the old playlist into the first blank. In the second, add a song of your own. Press run.
fix it
The film's name comes out as undefined. Fix it!
- The name shows as
undefined. Which key did destructuring look for? - Destructuring looks for a key with exactly the variable's name, and the film has no key called titel.
- Change titel to title on lines 2 and 3, then press run.
nailed it
you can unpack and copy like a pro. :D
const { a, b } = obj;unpacks keys into variables....spreads an array or object into a new one.- Spread copies, so the original never changes.
new words in your collection
- destructuring
- spread
This lesson isn’t saved. A free account remembers every lesson you finish.