DEV Community

Cover image for Variadic Functions in JavaScript - Understand the Basic Usage and Benefits
sahra πŸ’«
sahra πŸ’«

Posted on • Originally published at dev.to

Variadic Functions in JavaScript - Understand the Basic Usage and Benefits

Introduction

In this post you will learn what a variadic function is, the benefits of using one and when and why you might want to use it. Then we’ll take a look at how to create one in JavaScript. Read on to find out more!

Table of Content

What are Variadic functions?

These are functions that accept a variable number of arguments (255 being the limit). You can think of them as function grammars that support word endings such as, β€œa, b, c, and so on”. Variadic functions are also known as Varargs functions.

If a function takes a fixed number of arguments, it is not variadic. A variadic function can be used as a function that is not fixed to a specific number of arguments. You can pass it an arbitrary number of arguments.

Math.min() and Math.max() in JavaScript are also examples of variadic functions, as they are used to find the lowest or highest value in a list of arguments.

Benefits of using a variadic function in your Application

The main advantage of a variadic function is that it is more flexible than a function that takes a specific number of arguments. It also avoids having to create several different functions to handle different numbers of arguments.
Let’s say you want to create a function that sums up a variable number of integers.
If we try to use a normal function, we would only be limited to using a fixed number of arguments. Here is an example:

function sumall(arg1, arg2, arg3)
{
    let sum;

    sum = arg1 + arg2 + arg3;

    return sum;
}

let num = sumall(10,15,30);
console.log(num);
Enter fullscreen mode Exit fullscreen mode

console

45
Enter fullscreen mode Exit fullscreen mode

This function can only sum up the maximum of three arguments, which makes it very static.
Let's have a look at what would happen if we try to pass in more than three arguments.

let num2 = sumall(10, 15, 30, 35, 50);
console.log(num2);
Enter fullscreen mode Exit fullscreen mode

console

45
Enter fullscreen mode Exit fullscreen mode

We can see that we still got the same output, because the last two arguments added were ignored. But what we want is for all arguments to be added no matter how many are passed to the function, this is where variadic functions comes to the rescue.

When and why to use a variadic function?

Since a variadic function is one where the number of arguments is determined at run-time. It is often used to collect all the remaining arguments into a single list.

A variadic function is useful when you don’t know or don’t care how many arguments you’re going to receive. You can implement it to accept any number of inputs, which is handy when you’re dealing with user-input or other unpredictable data.

How to create a variadic function

Luckily creating a variadic function has been made quite easy in the JavaScript language unlike some other languages.

So to create a variadic function in JavaScript, we simply make use of the arguments keyword
The arguments keyword is used to create an Array-like object of all the arguments passed to the function when it is called. The object is only local to the function in which it is used. You can think of it as a local variable that is available with all functions by default except arrow functions in JavaScript.

Since the keyword provides an Array-like object of the arguments, we can access each argument by its index, and iteration of the arguments can also be done with the help of the .length property. All array methods can also be used to perform different operations on the arguments.
Now let's recreate our sumall function using the arguments keyword.

function sumall()
{
   let x = 0;
//iterate through the array of arguments and add each value to the x variable.
   for (let i = 0; i < arguments.length; ++i)
    x += arguments[i];

    return x;
}

//Lets call the function to calculate the sum of a varying list of argument and save the result to a variable.
let num1 = sumall(7, 9, 20);
let num2 = sumall(25, 73, 19, 32);

//Print out the values of the sums to the console.
console.log(num1);
console.log(num2);
Enter fullscreen mode Exit fullscreen mode

console

36
172
Enter fullscreen mode Exit fullscreen mode

We can see that no matter the number of arguments that we provide, the function is able to evaluate them all.

This is also very helpful when we want to perform certain computaions specifically for each arguments.

We can also pass whole Arrays as arguments to the function as well. We are able to do this by spreading the array values as individual arguments to the function using the spread operator Let's try to call our function again, but this time, pass in an array as one of the arguments.

//Sample array of integers to be passed.
let sampleArr = [3, 8, -16, 13, 18);
let num3 = sumall(10,20,30, ...sampleArr);

//Print out the value of the sum to the console.
console.log(num3);
Enter fullscreen mode Exit fullscreen mode

console

85
Enter fullscreen mode Exit fullscreen mode

You can see that it adds all the arguments passed to the function, as well as all the values in the array as well.

Alternatively, the rest operator which is denoted by an ellipsis (...) can be used instead of the arguments keyword.
This operator allows you to pass an arbitrary number of arguments after the first one. It’s available in a number of languages, including JavaScript.
It’s basically a placeholder that represents any remaining arguments after the first one. It is very similar in usage to the arguments keyword. Here is an example using it:

function sumall(...args)
{
   let x = 0;

   for (let i = 0; i < args.length; ++i)
    x += args[i];

    return x;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

As you can see, a variadic function is a powerful tool for creating flexible code that can adapt to any situation. A variadic function allows you to pass an arbitrary number of inputs to a function, which allows you to be more creative and make more practical use of the available inputs.

Top comments (7)

Collapse
 
weaves87 profile image
Andrew Weaver

Which method do you think is the cleaner one to use?

Personally, I think I'm more a fan of the sumall(...args) method using the spread syntax. It just feels so much more ES6-like

Collapse
 
sarahokolo profile image
sahra πŸ’«

I don't know, i kinda like the arguments keyword better, it seems to have a more abstract and cleaner feel to it, but i think also think the rest operator is nice in the sense that it makes it easier to spot out which of the functions in your code are variadic by just looking at their parameters.

Collapse
 
akuoko_konadu profile image
Konadu Akwasi Akuoko

Although the arguments keyword is fine to use, but it's kinda deprecated.

Thread Thread
 
sarahokolo profile image
sahra πŸ’«

Yeahh it kinda is, although I do like it as it seems just cleaner to use. It is not recommended to use in new developments. The rest parameters should be the preferred option.

Thread Thread
 
akuoko_konadu profile image
Konadu Akwasi Akuoko

Absolutely, a very nice article Sahra, I'm using some parts of your article in some notes I am writing, thanks πŸ‘

You on twitter?

Thread Thread
 
sarahokolo profile image
sahra πŸ’«

Thank you Konadu, I'm glad you found my article somewhat helpful. Yes I am on twitter. You can check out the link to my twitter profile in my bio

Thread Thread
 
akuoko_konadu profile image
Konadu Akwasi Akuoko

Just followed :)