Rest Parameter
The JavaScript Rest Parameter (…) allows functions to accept an arbitrary number of arguments as an array, simplifying the handling of variable-length parameter lists.
Syntax
// Triple Dots (...) is the Rest Parameter
function functionname( ...parameters ) {
statement;
};
Example 1: In this example, the sumFunction accepts any number of arguments and calculates their sum using the rest parameter.
Javascript
function sumFunction(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sumFunction(1, 2, 3, 4, 5)); |
15
Example 2: In this example, we perform array destructuring with the rest parameter to assign the first as 1, the second as 2, and the rest as [3, 4, 5] from the given array. It then prints these values.
Javascript
let [first, second, ...rest] = [1, 2, 3, 4, 5]; // Output: 1 console.log(first); // Output: 2 console.log(second); // Output: [3, 4, 5] console.log(rest); |
1 2 [ 3, 4, 5 ]
Both the Spread Operator & the Rest Operator can easily be distinguished. If the three dots (…) are specified at the end of function parameters, which defines the Rest parameters, which gathers all the other lists of arguments into an array, whereas, if three dots (…) occur in a function call, then it defines the Spread operator, that will expands an array into a list.
JavaScript Ellipsis
JavaScript Ellipsis (also known as the spread/rest operator) is represented by three dots (…). It is used for various tasks, such as spreading elements of an array into individual values or collecting multiple values into an array or object. It simplifies data manipulation and function parameter handling.
We will explore the basic implementation of the Spread/Rest operator with the help of examples.
Contact Us