Open In App

Variadic Functions in JavaScript

JavaScript variadic function is a function that can accept any number of arguments. In variadic functions no predefined number of function arguments is present that’s why a function can take any number of arguments. Also, there are some inbuilt functions in JavaScript that are variadic e.g.: min and max functions.

Syntax

function NameOfFun( x1, x2, x3, ... ){
// function body
}

There are a few approaches by using these you can create variadic functions in javascript:



Using arguments object

While JavaScript does not have native support for variadic functions. The arguments object is available inside every function and allows you to access all arguments passed to the functions. Even arguments do not declare explicitly in function. An argument object is like an array of arguments of functions.

Example: Creating a variadic function using an argument object






function SumOfNum() {
    let total = 0
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i]
    }
    return total;
}
  
console.log("Sum is ", SumOfNum(1, 2, 3, 4));
console.log("Sum is ", SumOfNum(1, 2, 5));

Output
Sum is  10
Sum is  8

Using Rest parameter

The rest parameter allows you to collect a variable number of arguments into an array parameter. To achieve variadic functions behavior using rest parameter, you can define a single argument inside a function using the rest operator.

Example: We have created a function for the sum of numbers without explicitly defining a fixed number of function parameters. On calling the function twice with a different number of arguments, it produced the correct result without triggering any errors.




function SumOfNum(...numbers) {
    let total = 0
    for (let i = 0; i < numbers.length; i++) {
        total += numbers[i]
    }
    return total;
}
  
console.log("Sum is ", SumOfNum(1, 2, 3, 4));
console.log("Sum is ", SumOfNum(1, 2, 5));

Output
Sum is  10
Sum is  8

Article Tags :