2

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 4

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

It's called a "rest parameter," FWIW.
@T.J.Crowder indeed, I just find "gather" and "spread" easier to explain to people, especially since the same operator does two opposite things depending on context.
:-) Quite. (Psst, neither rest nor spread is an operator. ;-) )
3

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']));

Comments

1

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.

Comments

1

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.