Skip to content
Codewilds

Lesson 21 of 34 · Objects

JavaScript Object Destructuring and Spread

medium20 XP3 min read

In the arrays chapter, destructuring and spread made working with lists shorter and safer. The same syntax works on objects, and that's where it really shines: function options, API responses, React props and state updates all use it constantly.

Object destructuring

Object destructuring pulls properties out into variables by name (not by position, as with arrays):

const hero = { name: "Ada", level: 7, guild: "Coders" };

const { name, level } = hero;
console.log(name, level); // Ada 7

You can rename a variable, give a default for a missing property, and reach into nested objects:

const { name: heroName } = hero;          // rename: heroName is "Ada"
const { mana = 50 } = hero;               // default: mana is 50 (hero has no mana)

const player = { stats: { str: 12, dex: 9 } };
const { stats: { str } } = player;        // nested: str is 12

The rest syntax collects every property you didn't name into a new object:

const { guild, ...rest } = hero;
console.log(rest); // { name: 'Ada', level: 7 }

Destructuring in function parameters

Destructuring is especially handy when a function receives an object. Instead of writing options.size and options.color all over the function, unpack what you need in the parameter list, defaults included:

function createPotion({ color = "red", size = "small" } = {}) {
  return `A ${size} ${color} potion`;
}

console.log(createPotion({ color: "blue" })); // A small blue potion
console.log(createPotion());                  // A small red potion

That final = {} matters. Without it, calling createPotion() with no argument would try to destructure undefined and throw a TypeError.

Passing an object of named options is a popular pattern because the call site documents itself ({ color: "blue" }) and the order of options doesn't matter.

Object spread: copying and merging

Spread syntax copies all properties of one object into a new object literal:

const base = { hp: 100, speed: 5 };
const copy = { ...base };

When several objects are spread, later properties win. That's the standard way to apply settings over defaults:

const defaults = { volume: 5, music: true, difficulty: "normal" };
const userChoices = { difficulty: "hard" };

const settings = { ...defaults, ...userChoices };
console.log(settings); // { volume: 5, music: true, difficulty: 'hard' }

Immutable updates

Spread lets you "change" an object by creating an updated copy, leaving the original untouched. Many libraries, including React, rely on this pattern:

const before = { name: "Ada", level: 7 };
const after = { ...before, level: before.level + 1 };

console.log(before.level); // 7
console.log(after.level);  // 8

Like array spread, object spread makes a shallow copy: nested objects are shared. If you need a fully independent deep copy, use structuredClone(obj).

Common mistakes

  • Destructuring undefined. const { a } = undefined throws. Give parameters a default = {}.
  • Spreading in the wrong order. { ...userChoices, ...defaults } lets the defaults overwrite the user's choices.
  • Expecting a deep copy. { ...hero }.inventory.push("gem") also changes hero.inventory.
  • Mixing up renaming and defaults. { name: heroName } renames; { name = "Anon" } sets a default. Combined: { name: heroName = "Anon" }.

Assignment

Write four functions:

  1. formatHero(hero) destructures name, role and level from the hero and returns "<name> the <role> (level <level>)". role defaults to "Adventurer" and level defaults to 1.
    • formatHero({ name: "Ada", role: "Mage", level: 3 }) → "Ada the Mage (level 3)"
    • formatHero({ name: "Bo" }) → "Bo the Adventurer (level 1)"
  2. createSettings(options) returns a new object that combines DEFAULT_SETTINGS (given in the starter) with options, where options wins. Calling createSettings() with no argument returns a copy of the defaults.
  3. levelUp(hero) returns a new hero object with level increased by 1. The original object must not change.
  4. toPublicProfile(user) returns a new object with every property of user except password and email.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 21 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.