How to use the spread operator with arrays and objects

· Category: JavaScript

Short answer

The spread operator ... expands an iterable into individual elements or copies enumerable properties from one object to another, enabling concise cloning and merging.

Steps

  1. Copy an array: javascript const copy = [...original];
  2. Merge arrays: javascript const merged = [...a, ...b];
  3. Copy and extend an object: javascript const updated = { ...user, role: "admin" };
  4. Merge objects: javascript const combined = { ...defaults, ...overrides };
  5. Convert a string or NodeList to an array: javascript const chars = ["hello"]; const items = [...document.querySelectorAll("li")];

Tips

  • Spread creates a shallow copy; nested objects still share references.
  • Later properties overwrite earlier ones when merging objects.

Common issues

  • Spreading null or undefined into an object throws an error in older transpilers; ensure the source is an object.
  • Attempting to spread an object into an array or vice versa throws a TypeError.