JavaScript single argument or array

Viewed 162

I have a JavaScript function which currently accepts one argument:

foo(country) { ... } and so is used like foo('US')

I need to extend this function to accept one or multiple countries:

foo('US')
foo('US', 'CA', 'UK')
foo(['US', 'CA', 'UK'])

Is any syntax/keyword feature for this? In C# we have a params keyword for this

4 Answers

Use a gather:

function(...args) {
   // do something with args
}

This is generally considered preferable to using arguments because arguments is a weird case: it isn't truly an array, hence the awkward old idiom you'll still sometimes see:

var args = Array.prototype.slice.call(arguments);

You could take rest parameters ... and flat the array.

function foo(...args) {
    return args.flat();
}

console.log(foo('US'));
console.log(foo('US', 'CA', 'UK'));
console.log(foo(['US', 'CA', 'UK']));

Yes. arguments.

foo(country){
    console.log(arguments)
}

It looks like an array. It's actually an object with numbered keys, but you can still loop through it and get the information you need.

arguments in function plays the same role as params in c#.

function foo() {
  console.log(arguments);
}

foo('a','b','c');
foo('a');

Related