CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 8 of 16: Spread and Rest
Part 8 of 16 · ~1 min

Spread and Rest

The spread operator (...) expands an iterable or object's own enumerable properties in place — commonly used for copying and merging without mutating the original.

const arr = [1, 2, 3];
const copy = [...arr, 4]; // [1, 2, 3, 4] — arr itself is untouched

const obj = { a: 1 };
const merged = { ...obj, b: 2 }; // { a: 1, b: 2 }
const overridden = { ...obj, a: 99 }; // { a: 99 } — later keys win, same as Object.assign order

The same ... syntax means something different in a function parameter list — there, it's rest, gathering any remaining arguments into a real array:

function sum(...numbers) { // rest — collects all arguments into an array
  return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10

function logFirst(first, ...rest) { // rest can follow named parameters too
  console.log(first, rest); // 1, [2, 3, 4]
}
logFirst(1, 2, 3, 4);

Spread only copies one level deep — nested objects/arrays are still shared by reference, which is the same shallow-copy trap Object.assign has:

const original = { user: { name: "Alice" } };
const copy = { ...original };
copy.user.name = "Bob";
console.log(original.user.name); // "Bob" — the nested object was never actually copied, just its reference

structuredClone(obj) (a built-in global in modern runtimes) performs a true deep copy, handling nested objects, arrays, Map, Set, and dates correctly — it's the standard modern replacement for the old JSON.parse(JSON.stringify(obj)) deep-clone hack, which silently drops functions, undefined values, and Date/Map/Set objects (turning dates into strings, and dropping Maps/Sets entirely).