Variadic Functions in D Programming Language

Here’s a function that will take an arbitrary number of ints as arguments.

function sum(...nums) {
    console.log(nums, " ");
    let total = 0;
    
    for (let num of nums) {
        total += num;
    }
    console.log(total);
}

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

To run the above code, you can simply put the function and its calls into a .js file and execute it using Node.js.

$ node your-file.js

Another key aspect of functions in JavaScript is their ability to form closures, which we’ll look at next.