optional variable in javascript

Is there there a way to specify an optional variable in a function call, then set it to a value if nothing is passed through

ie

function test(variable1, variable2 optional=0 )

then used test(1)

variable1 = 1 and variable2 = 0


Thanks
LVL 2
SometimesAsked:
Who is Participating?
 
RoonaanCommented:
Each parameter is optional by default, having "null" as an value.
You could therefor test using "==null" to assign another default value.

<script type="text/javascript">
function test(variable1, variable2)
{
 if(variable2 == null) variable2 = 0;
 alert("Var1: " + variable1 + "\nVar2:" + variable2);
}

test(10,11);
test(12);


</script>



-r-
0
 
SometimesAuthor Commented:
but in this case test(,12) doesn't work
0
 
RoonaanCommented:
No it doesn't. You could however always use: test(null, 12) and add an additional if-clause to the test() function.

Having calls like test(,,,,,12) however sound a bit VB-ish to me.. :^)

-r-
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.