How to create a javascript function with a variable number of parameters
1 min read

How to create a javascript function with a variable number of parameters

Since I am in the initial development phase for a new project, I'm doing a lot of debugging these days. In order to check things, I found myself console-logging variables so many times that it become a bit tiresome.

Let's say I had the variables a, b and c and I wanted to see what were their values. I had to write

console.log(a + ' / ' + b + ' / ' + c);
//example output "1 / 2 / 3"

I needed a way to shorten things up and to be able to do something like:

loggingFunction(a, b, c, '/');

and get the same output as above.

But things were tricky because I wouldn't always print just 3 variables. Maybe I will want to do it for 5, 6 or just 2.

A first solution would have been to pass the variables as an array, and do it like this

loggingFunction(['a', 'b', 'c'],  '/')

Somehow, the square brackets made it look ugly. So, after doing a little bit of research I found out you can make a javascript function that would be able to receive a variable number of parameters. All you need to do is declare a function without any parameters and then read any sent values from the arguments array.

Here is how I ended up doing my logging function after finding this out:

//console.log a list with its variables separated
function cl() {
    var str = '';
    var len = arguments.length - 1;
    var sep = arguments[len]; //the last argument is the separator

    //we decrease the len because we want to stop with one argument before the separator
    len -= 1;
    for (var i = 0; i < len; i+=1) {
       str += arguments[i] + ' ' + sep + ' ';
    }
    //now we add the last argument without the separator
    str += arguments[len];

    c(str);
}

Now, every time I want to print a list of variables, I just do this:

cl(a, b, c, d, '-');

and get a list of all my variables separated by a dash. Pretty useful, at least for me.

And the best part is that you can use the same principle to any other functions.