Home › Learn › JavaScript › Objects

Destructuring and spread

Lesson 23 of 40. Pull values out of objects and arrays, and copy or merge them.

Destructuring assigns parts of a structure to names in one line: const { name, age } = user; and const [first, second] = list;. It works in function parameters too, function greet({ name }), and supports defaults, { role = "guest" }, and renaming, { name: userName }. const [head, ...rest] = list collects the remaining items.

The spread operator ... copies: { ...defaults, ...options } builds a new object with the later keys winning, and [...a, ...b] joins arrays. Spread makes shallow copies, so nested objects are still shared.

const settings = { theme: "dark", size: 12 };
const { theme, size = 10, lang = "en" } = settings;
console.log(theme, size, lang);   // dark 12 en
const merged = { ...settings, size: 14 };
const [x, ...others] = [1, 2, 3];   // x = 1, others = [2, 3]

Your task

Write fullName({ first, last }) using parameter destructuring to return "First Last", merge(defaults, options) returning a new object with the options overriding the defaults (leaving both inputs unchanged), and firstAndRest(list) returning an object { first, rest } with the first item and an array of the others.

Hint 1

function fullName({ first, last }) { return `${first} ${last}`; }

Hint 2

return { ...defaults, ...options }; and const [first, ...rest] = list; return { first, rest };

Show the solution
function fullName({ first, last }) {
  return `${first} ${last}`;
}

function merge(defaults, options) {
  return { ...defaults, ...options };
}

function firstAndRest(list) {
  const [first, ...rest] = list;
  return { first, rest };
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.