0

I want to create a function in Javascript that has an optional array as parameter.

I was following this post but it not solved my question.

The function should be like this:

function myname (par1, par2, par3=[]){
//some script
}

or like this?

function myname (par1, par2, par3=false){
//some script
}

Any help?

Note: par3 is a parameter and must be an array if any.

In other words,

I would like a function in javascript similar to this one in php:

function myname ($par1,$par2, array $par3=NULL){
// some code        
}
Community
  • 1
  • 1
zwitterion
  • 3,958
  • 9
  • 43
  • 64
  • This depends entirely on what your function is doing. If it is expecting `par3` to be an array, then the former. – Jack Jan 19 '17 at 20:39
  • specifically what did you have a problem with the other post. – Daniel A. White Jan 19 '17 at 20:39
  • If you use your first example, `par3` will always be an empty array if you don't define it. In your second example `par3` will always be false if you don't define it. – Moose Jan 19 '17 at 20:40
  • @DanielA.White, the post show `delete_after = false`. That not works for me because my 3th parameter must be an array (=[]) AND must be false (=false) – zwitterion Jan 19 '17 at 20:57

1 Answers1

0

You need to use function and not funtion. There is typo mistake in your code.

function myname (par1, par2, par3=[]){
//some script
};
Abhinav Galodha
  • 7,820
  • 2
  • 27
  • 37
  • Hi Agalo it was a typo error. But this is not the issue. In your answer if I call myname(3,4) will be working ? – zwitterion Jan 19 '17 at 20:45
  • Yes, it will work. – Abhinav Galodha Jan 19 '17 at 20:47
  • I just tested. It is not working as expected. It calls myname(2,3); or myname(2,3,7); It should not work in the second scenario becaus p3 must be an array – zwitterion Jan 19 '17 at 20:54
  • Javascript is a dynamic language and you can change the type of a property. This is a language feature. But, you can check if the passed parameter is not an array and then ignore that parameter. `Array.isArray(param3)` – Abhinav Galodha Jan 19 '17 at 20:58
  • Ok I was trying to avoid check. If there is no way, Must to be checked. I made an update to compare with php. – zwitterion Jan 19 '17 at 21:03