Spread & Rest Operators

Published by Brayan K

Three little dots — ... — do two opposite jobs depending on where you write them. As spread they pour a collection out into its pieces; as rest they scoop loose pieces back into one collection.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Read the context before interpreting the dots

Spread expands values into a receiving array, object or argument list. Rest collects remaining values into a binding. The same dots appear in both forms, but the surrounding syntax determines the operation and the kind of input it accepts.

const first = ["A17", "B24"];
const second = ["C31"];
const combined = ["start", ...first, ...second];
// The new array has its own top-level list of elements.
console.log(JSON.stringify(combined));
console.log(JSON.stringify(first));
console.log(combined === first);

// ✅ Expected output:
// ["start","A17","B24","C31"]
// ["A17","B24"]
// false
const defaults = { colour: "blue", size: "small" };
const selected = { ...defaults, size: "large" };
console.log(JSON.stringify(selected));
console.log(JSON.stringify(defaults));
console.log(selected === defaults);

// ✅ Expected output:
// {"colour":"blue","size":"large"}
// {"colour":"blue","size":"small"}
// false

Array spread uses an iterable; object spread copies enumerable own properties. They are not interchangeable ways to turn any value into any container. Iterators & Iterables owns the iterable protocol.

const items = { 0: "A17", length: 1 };
console.log([...items]);

// ✅ Expected error:
// TypeError: items is not iterable
const codes = ["A17", "B24"];
const record = { ...codes };
console.log(JSON.stringify(record));
console.log(Array.isArray(record));

// ✅ Expected output:
// {"0":"A17","1":"B24"}
// false

The later property wins, even when its value is undefined

An object literal is built from left to right. Later entries with the same property key replace earlier values, whether those entries come from a spread or an explicit property. Write defaults first and intended overrides afterwards, then check what counts as an override in your contract.

const defaults = { size: "small", colour: "blue" };
const chosen = { size: "large" };
console.log(JSON.stringify({ ...defaults, ...chosen }));
console.log(JSON.stringify({ ...chosen, ...defaults }));

// ✅ Expected output:
// {"size":"large","colour":"blue"}
// {"size":"small","colour":"blue"}
const defaults = { limit: 10 };
const chosen = { limit: undefined };
const merged = { ...defaults, ...chosen };
console.log(Object.hasOwn(merged, "limit"));
console.log(merged.limit);

// ✅ Expected output:
// true
// undefined

Spreading is not a missing-value policy or a validation step. If undefined is supposed to mean "keep the default", implement that rule explicitly; Optional Chaining & Nullish Coalescing owns the relevant missing-value operators.

A fresh outer container can still share its nested data

Spread copies top-level values. When one of those values is an object or array, the copy receives the same reference. Updating a nested property through the copy can therefore change what the original sees.

const original = { label: "A17", settings: { colour: "blue" } };
const copy = { ...original };
copy.label = "B24";
copy.settings.colour = "green";
console.log(original.label);
console.log(original.settings.colour);
console.log(copy === original);
console.log(copy.settings === original.settings);

// ✅ Expected output:
// A17
// green
// false
// true
const original = { label: "A17", settings: { colour: "blue", large: false } };
const copy = {
  ...original,
  settings: { ...original.settings, colour: "green" }
};
console.log(JSON.stringify(original));
console.log(JSON.stringify(copy));
console.log(copy.settings === original.settings);

// ✅ Expected output:
// {"label":"A17","settings":{"colour":"blue","large":false}}
// {"label":"A17","settings":{"colour":"green","large":false}}
// false

Only the copied levels become independent. A deeper object inside settings would still be shared unless that level was also rebuilt. Arrays and Objects owns reference identity; copying a complete object graph is a different operation with its own type and behaviour constraints.

A shallow merge replaces whole nested properties

The same boundary matters when merging settings. A nested object is a value of one top-level property, so a later nested object replaces the whole earlier one. Object spread does not recursively merge corresponding keys.

const defaults = { display: { theme: "light", dense: false } };
const changes = { display: { dense: true } };
const merged = { ...defaults, ...changes };
console.log(JSON.stringify(merged.display));
console.log(Object.hasOwn(merged.display, "theme"));

// ✅ Expected output:
// {"dense":true}
// false

Merge a specific nested level when your schema requires it. A generic deep merge needs decisions about arrays, null, missing fields and allowed keys; this lesson does not pretend that recursively combining everything is always the correct policy.

Object spread copies selected property values, not every object feature

Only enumerable own properties participate. Inherited or non-enumerable properties are excluded, and the source prototype is not copied onto the new plain object. The fixture below makes those distinctions visible.

const source = Object.create({ inherited: "base" });
source.visible = "A17";
Object.defineProperty(source, "hidden", { value: "internal", enumerable: false });
const copy = { ...source };
console.log(copy.visible);
console.log(Object.hasOwn(copy, "inherited"));
console.log(Object.hasOwn(copy, "hidden"));

// ✅ Expected output:
// A17
// false
// false

The copied keys can include enumerable symbol keys as well as string keys. Object Methods (keys, entries, assign, freeze) owns property inspection and Symbols & Well-Known Symbols owns symbol keys; spread is not a complete object-cloning API.

A spread argument list differs from one array argument

When a function expects separate arguments, spreading an array supplies its values in separate argument positions. Passing the array without spread instead supplies one array value. Match the call to the function contract rather than choosing whichever syntax is shorter.

function describe(first, second) {
  console.log(Array.isArray(first));
  console.log(JSON.stringify(first));
  console.log(second);
}
const values = ["A17", "B24"];
describe(values);
describe(...values);

// ✅ Expected output:
// true
// ["A17","B24"]
// undefined
// false
// "A17"
// B24

Engines impose limits on argument counts, so spreading a very large collection into a function call is not a universal replacement for processing the collection. map, filter & reduce owns transformations and reductions that keep the values in an array.

Rest collects arguments into a new array

In a parameter list, rest gathers the arguments after the named parameters into an array. It can collect zero values. The rest parameter must come last because there is no later positional parameter left to fill after "the remaining arguments".

function pack(label, ...codes) {
  console.log(label);
  console.log(Array.isArray(codes));
  console.log(JSON.stringify(codes));
}
pack("batch", "A17", "B24");
pack("empty");

// ✅ Expected output:
// batch
// true
// ["A17","B24"]
// empty
// true
// []
function pack(...codes, label) {
  return label;
}
console.log(pack("A17", "batch"));

// ✅ Expected error:
// SyntaxError: Rest parameter must be last formal parameter

Rest is a parameter declaration, while spread is used at a call site. A function can collect arguments with rest and a caller can expand an array with spread, but neither step automatically knows which values the other intended as labels or data.

Rest in a pattern keeps the unselected values

Array rest gathers the remaining iterable values after the earlier positions. Object rest gathers remaining enumerable own properties after the named keys have been selected. Rest must be the last part of either pattern, and neither form removes values from the source.

const codes = ["A17", "B24", "C31"];
const [first, ...remaining] = codes;
console.log(first);
console.log(JSON.stringify(remaining));
console.log(JSON.stringify(codes));

const item = { sku: "A17", quantity: 2, colour: "blue" };
const { sku, ...details } = item;
console.log(sku);
console.log(JSON.stringify(details));
console.log(Object.hasOwn(details, "sku"));
console.log(Object.hasOwn(item, "sku"));

// ✅ Expected output:
// A17
// ["B24","C31"]
// ["A17","B24","C31"]
// A17
// {"quantity":2,"colour":"blue"}
// false
// true

The rest array or object is a new outer container, with the same shallow reference rule shown earlier. Destructuring Assignment owns selection, renaming and defaults in the rest of the pattern.

Complete an independent nested update

Copy the original record, then copy its settings before changing the colour to green. Fill both spread expressions from the literal hints. Check the original and updated settings and whether they still share the same nested object.

const original = { label: "A17", settings: { colour: "blue", large: false } };
const updated = {
  ___,
  settings: { ___, colour: "green" }
};
// 👉 replace ___ with ...original
// 👉 replace ___ with ...original.settings
console.log(JSON.stringify(original.settings));
console.log(JSON.stringify(updated.settings));
console.log(original.settings === updated.settings);

// ✅ Expected output:
// {"colour":"blue","large":false}
// {"colour":"green","large":false}
// false

Merge a known settings shape without losing nested defaults

Write mergeSettings(defaults, changes) for records with a display object. Top-level changes should override defaults, while display changes should override only corresponding display properties. Return a new outer record and a new display record. Test a size override and a dense-layout override, then print the original defaults to show they were not edited. This brief handles this known shape; it is not a general deep-merge utility.

function mergeSettings(defaults, changes) {
  return {
    ...defaults,
    ...changes,
    display: { ...defaults.display, ...changes.display }
  };
}
const defaults = {
  size: "small",
  display: { theme: "light", dense: false }
};
const changes = { size: "large", display: { dense: true } };
const merged = mergeSettings(defaults, changes);
console.log(JSON.stringify(merged));
console.log(JSON.stringify(defaults));
console.log(merged === defaults);
console.log(merged.display === defaults.display);

// ✅ Expected output:
// {"size":"large","display":{"theme":"light","dense":true}}
// {"size":"small","display":{"theme":"light","dense":false}}
// false
// false

The explicit nested merge preserves the theme while changing dense. Deeper nested values would still need their own decisions. A function named merge is only useful when its rules for each relevant part of the data are clear.

References: MDN documents spread syntax and shallow copies, rest parameters, and rest in destructuring patterns.

Practice quiz

What does this complete program print? const a = { size: "small" }; const b = { size: "large" }; console.log(({ ...a, ...b }).size);

  • large
  • small
  • undefined
  • TypeError: b is not iterable

Answer: large. The later property value replaces the earlier value with the same key.

What does this complete program print? const original = { settings: { value: 1 } }; const copy = { ...original }; copy.settings.value = 2; console.log(original.settings.value);

  • 1
  • 2
  • undefined
  • TypeError: Assignment to constant variable.

Answer: 2. The shallow copy retains the same nested settings object.

What does this complete program print? function count(...values) { return values.length; } console.log(count([1, 2])); console.log(count(...[1, 2]));

  • 2 2
  • 1 1
  • 1 2
  • 2 1

Answer: 1 2. The first call supplies one array argument; the second supplies two separate arguments.

What does this complete program print? const [first, ...rest] = ["A", "B", "C"]; console.log(first); console.log(JSON.stringify(rest));

  • A ["A","B","C"]
  • B ["C"]
  • A "C"
  • A ["B","C"]

Answer: A ["B","C"]. The first position is selected and array rest collects the remaining values.

What does this complete program print? const source = { code: "A", count: 2 }; const { code, ...rest } = source; console.log(Object.hasOwn(rest, "code")); console.log(Object.hasOwn(source, "code"));

  • false true
  • true true
  • false false
  • true false

Answer: false true. Object rest omits the selected key from the new object without deleting it from the source.

What does this complete program print? const value = { limit: 10, ...{ limit: undefined } }; console.log(value.limit);

  • 10
  • undefined
  • null
  • TypeError: Cannot convert undefined or null to object

Answer: undefined. An enumerable property whose value is undefined is still copied and overrides the earlier property.

What does this complete program print? const value = { ...["A", "B"] }; console.log(Array.isArray(value)); console.log(JSON.stringify(value));

  • true ["A","B"]
  • false ["A","B"]
  • false {"0":"A","1":"B"}
  • true {"0":"A","1":"B"}

Answer: false {"0":"A","1":"B"}. Object spread copies the array index properties into a plain object, not another array.

What does this complete program print? function list(label, ...values) { console.log(label, values.length); } list("empty");

  • empty undefined
  • undefined 0
  • TypeError: values is not iterable
  • empty 0

Answer: empty 0. With no remaining arguments, rest collects an empty array.

Continue this course

Related lessons