The Rest operator is introduced in ECMAScript 2015 (ES6). The Rest operator allows you to represent an indefinite number of arguments as an array. It allows you to handle multiple inputs as an argument in a function.
The Rest operator is prefixed with three dots (…). And if there are different type of arguments then only the last parameter can be a Rest parameter.
Syntax
function function_name(x, y, ...args) { // statement ... }
Let us understand with an example below.
function sum_func(...args) { let sum = 0; for (let i of args) { sum += i; } document.write("Sum = "+sum); } sum_func(10, 20, 30); #Output Sum = 60
function sum_func(name,...args) { let sum = 0; for (let i of args) { sum += i; } document.write(name); document.write("Sum = "+sum); } sum_func('Advance JS', 10, 20, 30); #Output Advance JS Sum = 60
Difference between Rest Parameter and Arguments Object
Both rest parameter and argument objects are different to each other.
The arguments object looks like an array but not actual array, whereas the rest parameters are an array instance. The arguments object does not use methods such as sort, map, for Each or pop etc., whereas these methods can be used directly in rest parameters.