Absolutely 👍 — here are several practical and clear examples of the rest operator (...
) in JavaScript, covering functions, arrays, and objects 👇
🧮 1. Rest in Function Parameters
When you don’t know how many arguments a function will receive:
👉 factor
gets the first argument (2
), and ...numbers
collects the rest into an array [1, 2, 3, 4]
.
🧑🤝🧑 2. Rest with Array Destructuring
You can collect remaining array elements into a variable:
👉 The rest operator gathers all remaining elements after the first two.
🗃️ 3. Rest with Object Destructuring
You can extract specific properties and collect the rest into a new object:
👉 Here, ...details
contains all other key-value pairs except name
.
🧑🏫 4. Rest in Arrow Functions
Useful in simple arrow functions that accept flexible parameters:
👉 The rest operator allows the function to accept any number of arguments.
🧩 5. Combining Named and Rest Parameters
Mixing normal parameters with rest: