# Spread vs Rest Operators in JavaScript

Modern JavaScript introduced powerful syntax using `...` that can behave in two different ways depending on context: **spread** and **rest**. While they look identical, their purpose is completely opposite.

Understanding this distinction is critical for writing clean, efficient, and interview-ready code.

* * *

## 🔹 What is the Spread Operator?

The **spread operator (**`...`**) expands values**.

It takes an iterable (like an array or object) and **spreads its elements out**.

### 👉 Simple Example

```js
const arr = [1, 2, 3];

const newArr = [...arr];

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

Here, `...arr` expands the array into individual elements.

* * *

## 🔹 Spread with Arrays

### 1\. Copying Arrays

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

✔ Creates a shallow copy ✔ Avoids reference issues

* * *

### 2\. Merging Arrays

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

const merged = [...a, ...b];
console.log(merged); // [1, 2, 3, 4]
```

* * *

### 3\. Adding Elements

```js
const arr = [2, 3];

const newArr = [1, ...arr, 4];
console.log(newArr); // [1, 2, 3, 4]
```

* * *

## 🔹 Spread with Objects

```js
const user = { name: "Sayantan" };

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

console.log(updatedUser);
// { name: "Sayantan", age: 21 }
```

### ✔ Common Use Case: Updating State (React / Immutability)

```js
const state = { count: 1 };

const newState = {
  ...state,
  count: state.count + 1
};
```

* * *

## 🔹 What is the Rest Operator?

The **rest operator (**`...`**) collects values**.

It gathers multiple elements into a single structure (array or object).

* * *

### 👉 Simple Example

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

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

Here, `...numbers` collects all arguments into an array.

* * *

## 🔹 Rest in Function Parameters

```js
function greet(first, ...others) {
  console.log(first);   // first value
  console.log(others);  // remaining values
}

greet("Hi", "Hello", "Hey");
// Hi
// ["Hello", "Hey"]
```

* * *

## 🔹 Rest with Destructuring (Arrays)

```js
const arr = [1, 2, 3, 4];

const [first, ...rest] = arr;

console.log(first); // 1
console.log(rest);  // [2, 3, 4]
```

* * *

## 🔹 Rest with Objects

```js
const user = {
  name: "Sayantan",
  age: 21,
  city: "Kolkata"
};

const { name, ...rest } = user;

console.log(name); // Sayantan
console.log(rest); // { age: 21, city: "Kolkata" }
```

* * *

## 🔥 Key Difference: Spread vs Rest

| Feature | Spread Operator (`...`) | Rest Operator (`...`) |
| --- | --- | --- |
| Purpose | Expands values | Collects values |
| Usage Context | Arrays, Objects, Function calls | Function params, Destructuring |
| Direction | Inside → Outside | Outside → Inside |

* * *

## 🧠 Mental Model (Very Important)

*   **Spread = EXPAND** → Break things apart → "Take values out"
    
*   **Rest = COLLECT** → Group things together → "Put values in"
    

* * *

## 🚀 Practical Use Cases

### 1\. Cloning Data (Avoid Mutation)

```js
const arr = [1, 2, 3];
const newArr = [...arr];
```

* * *

### 2\. Removing Properties from Objects

```js
const user = { id: 1, name: "Sayantan", password: "1234" };

const { password, ...safeUser } = user;

console.log(safeUser);
// { id: 1, name: "Sayantan" }
```

* * *

### 3\. Flexible Function Arguments

```js
function logAll(...args) {
  args.forEach(arg => console.log(arg));
}
```

* * *

### 4\. Combining Data (Real-world API Handling)

```js
const defaultConfig = { theme: "dark", lang: "en" };
const userConfig = { lang: "fr" };

const finalConfig = {
  ...defaultConfig,
  ...userConfig
};

console.log(finalConfig);
// { theme: "dark", lang: "fr" }
```

* * *

## ⚠️ Common Mistakes

### ❌ Confusing Context

```js
const arr = [1, 2, 3];

// Spread
console.log(...arr);

// Rest (invalid here ❌)
// const ...rest = arr;
```

👉 Same syntax, different meaning based on position.

* * *

### ❌ Shallow Copy Issue

```js
const obj = { a: { b: 1 } };

const copy = { ...obj };

copy.a.b = 2;

console.log(obj.a.b); // 2 ⚠️
```

👉 Spread does NOT deep clone.

* * *

## 🎯 Final Takeaway

*   Both use `...`, but:
    
    *   **Spread → expands values**
        
    *   **Rest → collects values**
        
*   Context determines behavior
    
*   Extremely common in **React, APIs, and interviews**
    

* * *

If you understand this deeply, you unlock a lot of modern JavaScript patterns.

* * *
