# 22. MEDIUM | Rest Parameters in JavaScript

* * *

**Rest parameters** **<mark class="bg-yellow-200 dark:bg-yellow-500/30">allow a function to accept an indefinite or variable number of arguments and collect them into a single, real array</mark>**. They are denoted by three dots (`...`) followed by a parameter name in the function definition.

Introduced in **ES6**.

### **Key Concepts**

*   **Syntax**: The syntax is `...parameterName`, where `parameterName` becomes an array within the function body.
    
*   **Position**: A function can have **only one rest parameter**, and it **must be the last parameter** in the function definition. This ensures it collects all *remaining* arguments after any explicitly defined parameters.
    
*   **Purpose**: They are used for creating "variadic functions" (functions that accept a variable number of arguments) and are a modern, cleaner alternative to the older `arguments` object.
    
*   **Real Arrays**: Unlike the `arguments` object, rest parameters are actual Array instances, meaning you can directly use standard array methods like `map()`, `filter()`, and `forEach()` on them.
    

### **Example**

```javascript
function func(a, b, c, ...d){
    console.log(a, b, c);
    console.log(d);
};

func(1, 2, 3, 4, 5, 6);
// 1, 2, 3
// [4, 5, 6]

func(1, 2, 3);
// 1, 2, 3
// []

func(1, 2);
// 1, 2, undefined
// []

func();
// undefined, undefined, undefined
// []
```

* * *

## **Rest Parameters vs. Spread Syntax**

Rest parameters use the same `...` syntax as the spread syntax, but they are opposites in function.

*   **Rest parameters** *collect* multiple elements into a single array (used in function *definitions*).
    
*   **Spread syntax** *expands* an array (or other iterable) into individual elements (used in function *calls* or array literals).
    

* * *

Happy reading!
