×

javascript · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.