intermediate

Rest and Spread Operators

Master the rest and spread operators for flexible function arguments.

The rest and spread operators, both written as three dots (...), are powerful ES6 features. Rest collects multiple elements into an array, while spread expands an array into individual elements. These operators make working with arrays and function arguments much more flexible and elegant.

📚 Concepts & Theory

Rest Operator (Collects into Array)

In function parameters:

function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}

sum(1, 2, 3, 4); // 10

With destructuring:

const [first, ...rest] = [1, 2, 3, 4];
// first = 1, rest = [2, 3, 4]

Spread Operator (Expands from Array)

Combining arrays:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]

Copying arrays:

const original = [1, 2, 3];
const copy = [...original];

Function arguments:

const numbers = [5, 10, 15];
Math.max(...numbers); // 15

With Objects

const base = { a: 1, b: 2 };
const extended = { ...base, c: 3 };
// { a: 1, b: 2, c: 3 }

🎯 Your Challenge

Create a function called `mergeArrays` that takes any number of arrays using rest parameters and returns a single merged array using spread. Test it with [1, 2] and [3, 4].

📝 Starter Code

JavaScript
// Function that merges any number of arrays
function mergeArrays(...arrays) {
    // Use spread to merge all arrays into one
    
}

// Test it
const result = mergeArrays([1, 2], [3, 4]);
// Should be [1, 2, 3, 4]
  • ...arrays in parameters is rest (collects)
  • ...array in expressions is spread (expands)
  • flat() merges nested arrays
  • Rest parameter must be last in parameter list

Solution

JavaScript
function mergeArrays(...arrays) {
    return arrays.flat();
}

const result = mergeArrays([1, 2], [3, 4]);

Explanation

The rest operator ...arrays collects all arguments into an array of arrays. We use flat() to merge them into a single array. Alternatively, you could use arrays.reduce((acc, arr) => [...acc, ...arr], []).

⚠️ Common Mistakes to Avoid

  • Confusing rest and spread (same syntax, different use)
  • Using rest in the wrong position (must be last)
  • Forgetting that spread creates shallow copies
  • Not understanding that rest creates an array

❓ Frequently Asked Questions

Yes! Spread works great with objects for merging and copying. Rest can be used in object destructuring to collect remaining properties.
No, spread creates a shallow copy. Nested objects and arrays are still references to the originals.

🔗 Related Exercises