Destructuring and Spread

Unpack values from objects and arrays into variables, rename and default them, and build new objects with ...spread.

JavaScript · beginner · 6 min · 8 steps · free

What you'll learn

Destructuring.js

const user = { name: 'Ada', age: 36, city: 'London' };
const { name, age } = user;
const { city: home } = user;
const [first, second = 'none'] = ['tea'];
const older = { ...user, age: 37 };
const merged = [...[1, 2], ...[3, 4]];
console.log(name, age, home, first, second);
console.log(user.age, older.age, merged);

Step by step

  1. user is created and points to a new Object: {name: "Ada", age: 36, city: "London"}.
  2. const { name, age } = user takes the matching properties into two variables.
  3. { city: home } takes the city property but names the variable home.
  4. Array destructuring goes by position. There is no second item, so second takes its default.
  5. { ...user, age: 37 } copies user's properties into a new object, then overrides age.
  6. merged is created and points to a new Array: [1, 2, 3, 4].
  7. It prints Ada 36 London tea none.
  8. user is unchanged: 36. older is a separate object: 37.

Common mistakes

Best practices

Key takeaways

Check yourself

const [a, b] = [1]; b is?

Answer: undefined

{ ...{ x: 1 }, x: 2 }.x?

Answer: 2. The later one wins.

·

More in Objects and Arrays