Variadic Functions ¶
See also
Contents
Description ¶
When you want to declare a function with variable number of parameters in Python, you take advantage of the special *args syntax.
The JavaScript equivalent would be the rest parameter defined with the spread (…) operator :
> function average(...numbers) {
if (numbers.length > 0) {
const sum = numbers.reduce((a, x) => a + x);
return sum / numbers.length;
}
return 0;
}
> average();
0
> average(1);
1
> average(1, 2);
1.5
> average(1, 2, 3);
2
The spread operator can also be used to combine iterable sequences.
For example, you can extract the elements of one array into another:
const redFruits = ['apple', 'cherry'];
const fruits = ['banana', ...redFruits];
fruits
Array(3) [ "banana", "apple", "cherry" ]
Depending on where you place the spread operator in the target list, you may prepend or append elements or insert them somewhere in the middle.