SyntaxStudy
Sign Up
JavaScript Intermediate 7 min read

Spread and Rest with Arrays

Spread and Rest with Arrays

The spread operator (...) and rest parameters were introduced in ES2015 and significantly simplified working with arrays and function arguments. They look identical syntactically but serve opposite purposes: spread expands an iterable into individual items, while rest collects individual items into an array.

Spread Operator

Place ... before an array (or any iterable) to expand its elements into a new context — a new array literal, a function call, or another spread expression. This is the cleanest way to copy or merge arrays without mutating originals.

Rest Parameters

In a function parameter list, ...args gathers all remaining arguments into a real array. Unlike the old arguments object, a rest parameter is a true array with all array methods available.

Practical Patterns

  • Shallow clone: const copy = [...original]
  • Merge: const merged = [...a, ...b]
  • Prepend/append: const newArr = [0, ...arr, 99]
Example
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b];
console.log(merged); // [1,2,3,4,5,6]
const copy = [...a];
copy.push(99);
console.log(a);    // [1,2,3] — untouched
console.log(copy); // [1,2,3,99]
function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
const nums = [3, 1, 4, 1, 5];
console.log(Math.max(...nums)); // 5
Pro Tip

The spread copy is shallow — nested objects are still shared by reference. Use structured clone (structuredClone()) or a JSON round-trip when you need a deep copy.