Kodokon kodokon.com

Destructuring and spread/rest

Cleanly extract data from objects and arrays, then copy and merge structures with the spread operator.

8 min · 3 questions

Open this lesson in Kodokon

When you receive data from an API, you often only need a few properties. Destructuring extracts them in one line, with the option to rename, reach into nested objects, and provide a default value if the property is missing.

JAVASCRIPT
const user = {
  id: 42,
  name: "Lea",
  address: { city: "Lyon", zip: "69001" }
};

const { name, address: { city } } = user;
const { role = "guest" } = user;

console.log(name, city, role); // "Lea" "Lyon" "guest"
Nested extraction and a default value when the property is missing.

Destructuring also works on arrays, this time by position. Its most professional use remains function parameters: instead of receiving an opaque object, the signature announces exactly which properties are expected. The code becomes self-documenting.

JAVASCRIPT
const podium = ["gold", "silver", "bronze"];
const [first, , third] = podium;
console.log(first, third); // "gold" "bronze"

function formatUser({ name, role = "guest" }) {
  return `${name} (${role})`;
}

console.log(formatUser({ name: "Sam" }));
// "Sam (guest)"
Array destructuring by position and function parameter destructuring.

The same ... operator has two faces. As spread, it expands an array or object to copy or merge it: widely used to apply default settings and then override them. As rest, it gathers "everything that's left" into an array, for example to accept a variable number of arguments.

JAVASCRIPT
const baseConfig = { theme: "dark", lang: "fr" };
const overrides = { lang: "en" };
const config = { ...baseConfig, ...overrides };
// { theme: "dark", lang: "en" }

const scores = [12, 18, 9];
const allScores = [...scores, 20]; // [12, 18, 9, 20]

function sumAll(...numbers) {
  return numbers.reduce((sum, n) => sum + n, 0);
}
console.log(sumAll(1, 2, 3)); // 6
Spread to merge, rest to gather: merge order matters.

Mental exercise before moving on to the quiz: in { ...baseConfig, ...overrides }, what happens if both objects define lang? The last one written wins. This ordering detail is exactly what makes the "defaults then overrides" pattern possible.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does the line const { city } = user; do?
    • It creates a city variable containing user.city
    • It renames the user object to city
    • It creates a new empty object named city
  2. In function log(...args), what is args inside the function?
    • A key-value object
    • A real array containing all the received arguments
    • A string
    • The first argument only
  3. After const copy = { ...original };, are nested objects duplicated?
    • Yes, the copy is fully independent
    • No, they remain shared: the copy is shallow
    • They are removed from the copy