Is it possible to do the following (or an equivalent):
function a(foo, bar[x]){
//do stuff here
}
Thanks in advance.
asked Aug 21, 2014 at 17:30
user3616018
2 Answers 2
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.
answered Aug 21, 2014 at 17:40
user949300
15.7k7 gold badges39 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Aug 21, 2014 at 17:35
bto.rdz
6,7404 gold badges41 silver badges56 bronze badges
lang-js
barfits. You can't expect an array, but you can validate the argument at the top of the body.