Skip to main content
Known Participant
November 19, 2009
Question

bypassing function argument without changing default value

  • November 19, 2009
  • 2 replies
  • 451 views

Hi there
I’m having some problems understanding how I can bypass function arguments without changing its default value. Here are some examples:

function myFunction ( arg1:Boolean, arg2:String="default string", arg3:Number=3 ):Array
{
    return new Array (arg1, arg2, arg3);
}

trace(myFunction(true, "new string", 5));
// true,new string,5

trace(myFunction(true, undefined, 5));
// true,,5

trace(myFunction(true, null, 5));
// true,,5

trace(myFunction(true));
// true,default string,3

trace(myFunction(true, null));
// true,,3

My question is: Shouldn't I be able to call a function bypass the second argument (that has a default value), change third argument and on result second argument maintains its default value?
Example:

trace(myFunction(true, null, 5));
// not desired: true,,5
// desired: true,default string,5

I know that applying a defult value to the argument allows one to bypass it. But it will always be redefined or to null or to undefined. At the moment I only see one solution.

function myFunction ( arg1:Boolean, arg2:String="default string", arg3:Number=3 ):Array
{
     if (!arg2)arg2 = "deafult string";
     return new Array (arg1, arg2, arg3);
}



It just seems like too much code repeated
Regards
This topic has been closed for replies.

2 replies

November 19, 2009

This is no way to simply skip a function argument. The simple answer is because there would be no way to tell if you wanted to skip that argument, or if you intended the 3rd argument for the second and were leaving the 3rd blank. In other languages, like C++, there is function overloading which would allow for something like this. You would need to define two versions of the same function though with different argument types. Simply testing for a null value and applying a default (like you have) is actually the easiest method.

Known Participant
November 19, 2009

I have to agree AHernandezIP

Thank you all for your replies.

November 19, 2009

Yeah... from what I've seen the only way the default is used is if there is truly nothing passed to its argument.

You will either need to test for null or undefined, or you could possibly switch your parameters order:

function myFunction(arg1:Number, arg2:Number = 3, arg3:String = "Default String")

But that may not work for you.

Known Participant
November 19, 2009

Hi dmennenoh,


Yup, this was just an example to show that the use of a default value only helps you to bypass the need to simulate a MouseEvent Object for an onRollOver MouseEvent argument. Other than that you can never bypass it without changing its value. You must always apply a null or undefined value and work with that.

Thanks anyway