Variadic Functions in JavaScript
Variadic functions can be called with any number of trailing arguments. For example, console.log
is a common variadic function.
Here’s a function that will take an arbitrary number of number
s as arguments.
function sum(...nums) {
console.log(nums, " ");
let total = 0;
for (let num of nums) {
total += num;
}
console.log(total);
}
sum(1, 2);
sum(1, 2, 3);
let nums = [1, 2, 3, 4];
sum(...nums);
Here’s a function that will take an arbitrary number of number
s as arguments. Within the function, the type of nums
is equivalent to number[]
. We can get its length, iterate over it using loops, etc.
Variadic functions can be called in the usual way with individual arguments.
sum(1, 2); // Output: [1, 2] 3
sum(1, 2, 3); // Output: [1, 2, 3] 6
If you already have multiple args in an array, apply them to a variadic function using func(...array)
like this.
let nums = [1, 2, 3, 4];
sum(...nums); // Output: [1, 2, 3, 4] 10
Now that we can use variadic functions in JavaScript, let’s learn more about the language.