Skip to article content
FrontendXLesson 15 / 30

Destructuring, Spread and Rest

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 35 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Extract values from arrays and objects with defaults and renaming.
  • Use spread to build new arrays and objects without mutating the source.
  • Recognize that spread and Object.assign copy only one level deep.

Overview

#

Destructuring

Destructuring binds names to values pulled out of an array or object. Array patterns go by position, object patterns go by key. Defaults fill in missing values, and a colon renames the bound variable.

snippet.js
const [first, second = 2] = [1];
const { name: label, size = 'm' } = { name: 'tee' };
console.log(first, second, label, size); // 1 2 tee m

Rest and spread

The rest syntax collects the remaining items into a new array or object. Spread does the reverse and expands an iterable or object into a new literal. Together they replace manual copying and argument slicing.

snippet.js
const nums = [1, 2, 3];
const [head, ...tail] = nums;
console.log(head, tail, [...nums, 4]); // 1 [2,3] [1,2,3,4]

The shallow copy trap

Spread and Object.assign copy own enumerable properties one level deep. Nested objects are still shared by reference, so mutating a nested value through the copy also changes the original. For a true independent copy use structuredClone, and for immutable updates rebuild each level you change.

snippet.js
const base = { nested: { count: 1 } };
const next = { ...base };
next.nested.count = 2;
console.log(base.nested.count); // 2, the nested object was shared

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const { a = 1, b: { c = 2 } = {} } = { a: undefined };
    console.log(a, c);
    Choose the best answer
  2. Exercise 2Explain

    Explain why `{ ...base }` is not a safe way to update a nested value immutably.

    starter.text
    const next = { ...base };
    next.nested.count = 2;

    Reveal the reference answer
    reference.text
    Spread copies the top-level properties, but the value of nested is a reference to the same object as in base. Writing to next.nested.count therefore mutates the shared object and base sees the change. To update immutably I copy each level along the path, for example { ...base, nested: { ...base.nested, count: 2 } }, or use structuredClone for an independent copy.

    Authored expected output: base.nested.count becomes 2

    Shallow copy is the key idea. Immutable updates must rebuild every level that changes, not just the top one.

  3. Exercise 3Implement

    Implement `pick(source, keys)` so it returns a new object with only the listed keys. Running `console.log(JSON.stringify(pick({ a: 1, b: 2, c: 3 }, ['a', 'c'])))` should print `{"a":1,"c":3}`.

    starter.javascript
    function pick(source, keys) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function pick(source, keys) {
      return keys.reduce((acc, key) => {
        if (key in source) acc[key] = source[key];
        return acc;
      }, {});
    }

    Authored expected output: {"a":1,"c":3}

    Reducing over the keys builds a fresh object and copies only the requested properties. Checking with in avoids adding keys that are absent.

  4. Exercise 4Debug

    This function is meant to add a tag without changing the input, but the input changes. Find and fix the bug.

    starter.javascript
    function addTag(post, tag) {
      post.tags.push(tag);
      return post;
    }
    const p = { tags: ['a'] };
    addTag(p, 'b');
    console.log(p.tags.length);

    Reveal the reference answer
    reference.javascript
    function addTag(post, tag) {
      return { ...post, tags: [...post.tags, tag] };
    }
    const p = { tags: ['a'] };
    addTag(p, 'b');
    console.log(p.tags.length);

    Authored expected output: 1

    The original mutates the shared tags array with push. Spreading the post and the tags creates new objects, so the caller's value keeps length 1.

  5. Exercise 5Test

    Write assertions that prove rest collects the remainder and spread does not mutate the source.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value');
    }

    Reveal the reference answer
    reference.javascript
    const nums = [1, 2, 3];
    const [head, ...rest] = nums;
    assertEqual(head, 1, 'head is first');
    assertEqual(rest, [2, 3], 'rest keeps the remainder');
    const copy = [...nums, 4];
    assertEqual(nums, [1, 2, 3], 'source array is unchanged');
    assertEqual(copy, [1, 2, 3, 4], 'copy has the new item');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    Rest gathers the remaining elements into a new array. Spreading into a new literal leaves the original array untouched.

  6. Exercise 6Interview

    How do you update nested state without mutating the previous value?

    Reveal the reference answer
    reference.text
    I copy each level from the root down to the changed key, so every ancestor is a new object and untouched siblings keep their reference. For plain data I use spread at each level, and for a fully independent copy I use structuredClone. I avoid in-place methods such as push and sort on state, and I keep the update logic in one place so the pattern is consistent.

    The answer should name path copying, new ancestors, shared untouched siblings and the shallow nature of spread.

Common misconceptions

#
  • Spread performs a deep copy of nested objects.
  • A rest parameter in a function must be the first parameter.
  • Object destructuring matches keys in declaration order.

Follow-up practice

#
  • javascript-foundations-objects-and-prototypes
  • javascript-foundations-functional-programming-and-currying

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.