0

Is it possible to do the following (or an equivalent):

function a(foo, bar[x]){
    //do stuff here
}

Thanks in advance.

4
  • 1
    This is not valid syntax. What are you trying to accomplish? Commented Aug 21, 2014 at 17:33
  • 1
    Javascript is not a static language, so just bar fits. You can't expect an array, but you can validate the argument at the top of the body. Commented Aug 21, 2014 at 17:33
  • 1
    No, that make no sense :) what are you trying to do exactly? Commented Aug 21, 2014 at 17:33
  • What you should be doing is to resolve the bar[x] first and pass THAT into the function. Commented Aug 21, 2014 at 17:34

2 Answers 2

3

Since JavaScript is not statically typed, you cant insist on an array. You can do something like this: (far from perfect but usually does the job)

function a(foo, bars) {
  if (!Array.isArray(bars))
    bars = [bars];

  // now you are sure bars is an array, use it
}

I find that naming arrays in the plural, e.g. "bars" instead of "bar", helps, YMMV.

Sign up to request clarification or add additional context in comments.

Comments

0

yes, it is possible, as you have noticed you never especify de type of your variables, you only do var a = 1 so here is the same case, you dont have to tell javascript it is an array, just pass it, it will work

function myFunction(foo, array){

}

and the call

var myFoo = { name: 'Hello' };
var myArray = [ 1, 2 ]
myFunction(myFoo, myArray);

hope it helps

1 Comment

That's answered my question! Thank you!