0
0
JavascriptConceptBeginner · 3 min read

What is Rest Operator in JavaScript: Simple Explanation and Examples

The rest operator in JavaScript is written as ... and allows you to collect multiple elements into a single array. It is commonly used in function parameters to gather all remaining arguments into one array or to destructure arrays and objects easily.
⚙️

How It Works

The rest operator looks like three dots ... and acts like a collector. Imagine you have a basket and you want to gather all leftover fruits into it. The rest operator does the same but with values in code.

When used in function parameters, it collects all extra arguments passed into one array. When destructuring arrays or objects, it gathers the remaining items or properties into a new array or object. This helps keep your code clean and flexible.

💻

Example

This example shows how the rest operator collects extra arguments into an array inside a function.

javascript
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3));
console.log(sum(4, 5));
Output
6 9
🎯

When to Use

Use the rest operator when you want to handle an unknown number of function arguments without listing them all. It is also helpful when you want to separate some elements from an array or properties from an object and keep the rest grouped together.

For example, in event handlers, you might want to accept many parameters. Or when working with arrays, you can easily split the first few items and keep the rest in another array.

Key Points

  • The rest operator is written as ... and collects remaining elements.
  • It creates an array of leftover function arguments or array elements.
  • It helps write flexible functions that accept any number of arguments.
  • It works with array and object destructuring to group remaining items.

Key Takeaways

The rest operator ... collects multiple values into one array.
It is useful for functions that accept any number of arguments.
It simplifies working with arrays and objects by grouping leftover elements.
Use it to write cleaner and more flexible JavaScript code.