JavaScript ยท Chapter 40 of 55

JavaScript Spread & Rest Operators

The spread operator `...` expands an array or object into individual elements, useful for copying, merging, or passing multiple arguments to a function.

The rest operator uses the same `...` syntax but works oppositely โ€” it gathers multiple values into a single array, commonly used in function parameters.

Spread

`[...arr1, ...arr2]` merges two arrays. `{...obj1, ...obj2}` merges two objects, with later properties overriding earlier ones.

Rest parameters

`function sum(...nums) { ... }` collects any number of arguments into a single array called nums.

Example 1 (javascript)
let a = [1, 2];
let b = [3, 4];
let merged = [...a, ...b];
console.log(merged);
Output
[1, 2, 3, 4]

Spread expands both arrays into a new combined array.

Example 2 (javascript)
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));
Output
10

Rest parameters gather all arguments into a nums array.

Key points

  • Spread (`...`) expands an iterable into individual elements.
  • Rest (`...`) gathers multiple arguments into one array.
  • Spread is great for copying and merging arrays/objects.
  • Rest parameters must be the last parameter in a function.
๐Ÿ’ก Note: Spread creates a shallow copy โ€” nested objects/arrays are still shared by reference.

๐Ÿ“ Quick Quiz

1. What does spread do to an array?

2. What does rest do in a function parameter?

3. Where must a rest parameter appear?