Curriculum / Intermediate / Lesson 13

Spread & Rest Operators

Copy, merge, and collect data with ... syntax.

13 of 30
intermediate 📖 5 min read 🎯 3 questions

What is the Spread Operator?

The spread operator (...) "spreads" the elements of an array or object into a new array, object, or function arguments.

💡 Key insight The spread operator creates a shallow copy — it copies the top-level structure, but nested objects are still shared by reference.

Spread with Arrays

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

// Copy an array
let copy = [...arr1]; // [1, 2, 3]

// Merge arrays
let merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

// Add elements
let newArr = [0, ...arr1, 4]; // [0, 1, 2, 3, 4]

Spread with Objects

let obj1 = { name: "Alice", age: 25 };
let obj2 = { city: "New York", country: "USA" };

// Copy an object
let copy = { ...obj1 };

// Merge objects
let merged = { ...obj1, ...obj2 };

// Override properties (last one wins)
let updated = { ...obj1, age: 26 };

Rest Parameters

The rest operator collects remaining elements into an array.

// In function parameters
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10

// In array destructuring
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]

Common Mistakes

Quick Quiz

1. What does [...arr1, ...arr2] do?

2. What does the rest operator do in function sum(...args)?

3. Which is correct for copying an object?

Summary

Back to curriculum