JS Learning

ES6+ Features

Lesson Progress0%

Section 2 of 4

Spread & Rest

Spread & Rest

Topic Overview

Take your time to understand each concept. Practice with the examples below!

The three dots (...) operator is like magic - it can either spread things out or gather them together. Think of it as either unpacking a box (spread) or packing things into a box (rest).

Spread Operator - Spreading/Expanding:

1. Combining Arrays:
const fruits = ["apple", "banana"];
const vegetables = ["carrot", "broccoli"];
const food = [...fruits, ...vegetables];
// Result: ["apple", "banana", "carrot", "broccoli"]
2. Copying Arrays (without affecting original):
const original = [1, 2, 3];
const copy = [...original];
copy.push(4); // original is still [1, 2, 3]
3. Combining Objects:
const defaults = { color: "blue", size: "medium" };
const userChoice = { size: "large" };
const final = { ...defaults, ...userChoice };
// Result: { color: "blue", size: "large" }
4. Function Arguments:
const numbers = [5, 10, 15];
Math.max(...numbers); // Same as Math.max(5, 10, 15)

Rest Operator - Gathering/Collecting:

1. Function Parameters:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // numbers = [1, 2, 3, 4]
2. Array Destructuring:
const [first, ...others] = ["a", "b", "c", "d"];
// first = "a", others = ["b", "c", "d"]
3. Object Destructuring:
const { name, ...details } = { name: "Alice", age: 30, city: "NYC" };
// name = "Alice", details = { age: 30, city: "NYC" }

Practical uses:

  • Merge configuration objects
  • Clone arrays/objects safely
  • Pass array items as arguments
  • Collect remaining parameters
  • Remove properties from objects

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Use spread operator to combine arrays and objects, and rest to collect remaining values.

Loading...