Skip to main content

Command Palette

Search for a command to run...

Spread vs Rest Operator in JavaScript โ€” Explained Simply

Updated
โ€ข3 min read
Spread vs Rest Operator in JavaScript โ€” Explained Simply

JavaScript introduced the spread (...) and rest (...) operators in ES6. They look identical but behave very differently depending on where they are used.


1. What is the Spread Operator?

The spread operator (...) expands elements.

It takes an iterable (like an array or object) and spreads it into individual elements.

Example (Array Expansion)

const arr = [1, 2, 3];

const newArr = [...arr, 4, 5];

console.log(newArr);
// [1, 2, 3, 4, 5]

Example (Function Arguments)

const nums = [1, 2, 3];

function sum(a, b, c) {
  return a + b + c;
}

console.log(sum(...nums)); // 6

๐Ÿ‘‰ Think: Spread = Expand values


2. What is the Rest Operator?

The rest operator (...) collects multiple elements into one.

It is mainly used in:

  • Function parameters

  • Destructuring

Example (Function Parameters)

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

console.log(sum(1, 2, 3, 4)); // 10

Example (Array Destructuring)

const [first, ...rest] = [10, 20, 30, 40];

console.log(first); // 10
console.log(rest);  // [20, 30, 40]

๐Ÿ‘‰ Think: Rest = Collect values


3. Spread vs Rest (Key Differences)

Feature Spread Operator Rest Operator
Purpose Expands elements Collects elements
Usage Arrays, objects, function calls Function params, destructuring
Direction One โ†’ Many Many โ†’ One
Example [...arr] (...args)

4. Using Spread with Arrays

Copying Arrays

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

Merging Arrays

const a = [1, 2];
const b = [3, 4];

const merged = [...a, ...b];
// [1, 2, 3, 4]

Adding Elements

const nums = [2, 3];
const updated = [1, ...nums, 4];
// [1, 2, 3, 4]

5. Using Spread with Objects

Copying Objects

const user = { name: "Pritam", age: 22 };

const copyUser = { ...user };

Updating Properties

const updatedUser = { ...user, age: 23 };

Merging Objects

const a = { x: 1 };
const b = { y: 2 };

const merged = { ...a, ...b };
// { x: 1, y: 2 }

6. Practical Use Cases

1. React State Updates

setUser({ ...user, age: 23 });

2. Removing Items from Array

const items = [1, 2, 3, 4];

const newItems = items.filter(item => item !== 2);

3. Function with Unlimited Arguments

function logAll(...args) {
  console.log(args);
}

4. Cloning Without Mutation

const newArr = [...oldArr];

7. Simple Mental Model (Very Important)

  • Spread (...) โ†’ Expands

    [1,2,3] โ†’ 1,2,3
    
  • Rest (...) โ†’ Collects

    1,2,3 โ†’ [1,2,3]
    

8. Visual Diagram Idea

Spread (Expanding)

[1, 2, 3]
   โ†“
1   2   3

Rest (Collecting)

1   2   3
   โ†“
[1, 2, 3]

Final Thoughts

Even though both use ..., their behavior is opposite:

  • Spread โ†’ breaks things apart

  • Rest โ†’ puts things together

If you understand this one line, youโ€™ll never confuse them again.