Rest Parameters

Introduction

Rest Parameters in JavaScript allow functions to accept an indefinite number of arguments as an array. This makes your code more flexible and easier to manage when working with multiple inputs.

Understanding Rest Parameters

Rest Parameters use three dots before a parameter name. This syntax collects all remaining arguments into a single array. It is especially useful when you do not know how many arguments will be passed to a function.

Syntax

function functionName(…params)
params represents an array containing all extra arguments

Example

function sum(…numbers) {
let total = 0
for (let num of numbers) {
total += num
}
return total
}

console.log(sum(10, 20, 30))

In this example, all values passed into the function are gathered into the numbers array.

Key Features

Rest Parameters collect multiple values into one variable
They simplify function definitions when handling many inputs
They return an array, allowing use of array methods
They improve code readability and flexibility

Rules for Using Rest Parameters

Only one rest parameter is allowed in a function
It must be the last parameter in the function
It gathers remaining arguments after named parameters

Example with Other Parameters

function greet(message, …names) {
return message + ” ” + names.join(“, “)
}

console.log(greet(“Hello”, “Ali”, “Sara”, “Ahmed”))

Difference Between Rest Parameters and Spread Operator

Rest Parameters collect arguments into an array
Spread Operator expands elements from an array or object

Use Cases

Handling multiple user inputs
Creating reusable utility functions
Working with dynamic data sets
Simplifying function arguments

Conclusion

Rest Parameters make JavaScript functions more powerful and flexible. They help developers write cleaner code by managing multiple arguments efficiently.

Home » Advanced JavaScript > ES6+ Features > Rest Parameters