JavaScript rest parameter denoted by three dots (…) is used to represent an indefinite number of arguments as an array. A function can be called with any number of arguments, regardless of how it was defined.
Syntax
function f(x, y, ...args) {
// ...
}
One thing to remember is that only the last parameter can be a Rest Parameter.
Visual Representation
Example 1: How to Use the rest parameter
function multiplication(...args) {
return args.reduce((accumulator, current) => accumulator * current);
};
console.log(multiplication(1, 3, 5, 7, 9));
Output
945
Example 2: Passing other arguments
function func (a, b, ...manyMoreArgs) {
console.log(a);
console.log(b);
console.log('manyMoreArgs', manyMoreArgs);
console.log(manyMoreArgs[0]);
console.log(manyMoreArgs.indexOf('wolves'));
console.log(manyMoreArgs.length);
};
func('mia', 'despacito', 'attention', 'wolves', 'sorry');
Output
mia
despacito
manyMoreArgs [ 'attention', 'wolves', 'sorry' ]
attention
1
3
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.