How to use Rest parameter In Javascript
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.
Javascript
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)); |
Sum is 10 Sum is 8
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 argument object
- Using rest parameter