You can access the arguments passed to any JavaScript function via the magic arguments object, which behaves similarly to an array. Using arguments your function would look like:
var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}
This will not help if you don't know the number of arguments, but it helps if you don't want to remember the order of them.
/**
* @param params.one A test parameter
* @param params.two Another one
**/
function test(params) {
var one = params.one;
if(typeof(one) == 'undefined') {
throw new Error('params.one is undefined');
}
var two = params.two;
if(typeof(two) == 'undefined') {
throw new Error('params.two is undefined');
}
}
function printNames(...names) {
console.log(`number of arguments: ${names.length}`);
for (var name of names) {
console.log(name);
}
}
printNames('foo', 'bar', 'baz');
There are three main differences between rest parameters and the
arguments object:
rest parameters are only the ones that haven't been given a separate name, while the arguments object contains all
arguments passed to the function;
the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
the arguments object has additional functionality specific to itself (like the callee property).
You can use the spread/rest operator to collect your parameters into an array and then the length of the array will be the number of parameters you passed: