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
- Copy an array:
javascript const copy = [...original]; - Merge arrays:
javascript const merged = [...a, ...b]; - Copy and extend an object:
javascript const updated = { ...user, role: "admin" }; - Merge objects:
javascript const combined = { ...defaults, ...overrides }; - 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
nullorundefinedinto 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.