Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

empty arguments

Status
Not open for further replies.

jimmyshoes

Programmer
Jun 1, 2008
132
GB
Is it acceptable to leave arguments empty
for example
Code:
<script>

function showIt(a,b,c){
if(a) alert(a);
if(b) alert(b);
if(c) alert(c);
}

showIt(1,2,3);
showIt(1);
showIt(1,null,null);

</script>

is showIt(1); ok or should you always use showIt(1,null,null);
 
Hi

jimmyshoes said:
is showIt(1); ok or should you always use showIt(1,null,null);
It is Ok.

But note that your [tt]if[/tt] condition will be evaluated to false not only when the given argument misses, but also when the following values are passed : [tt]false[/tt], 0, '', [tt]null[/tt], [tt]NaN[/tt], [tt]undefined[/tt]. The proper [tt]if[/tt] condition should be [tt]a!=undefined[/tt].

However the proper way to do it is to check the argument count :
JavaScript:
[b]function[/b] [COLOR=darkgoldenrod]showIt[/color][teal]([/teal]a[teal],[/teal]b[teal],[/teal]c[teal])[/teal]
[teal]{[/teal]
  [b]if[/b] [teal]([/teal]arguments[teal].[/teal]length[teal]>=[/teal][purple]1[/purple][teal])[/teal] [COLOR=darkgoldenrod]alert[/color][teal]([/teal]a[teal]);[/teal]
  [b]if[/b] [teal]([/teal]arguments[teal].[/teal]length[teal]>=[/teal][purple]2[/purple][teal])[/teal] [COLOR=darkgoldenrod]alert[/color][teal]([/teal]b[teal]);[/teal]
  [b]if[/b] [teal]([/teal]arguments[teal].[/teal]length[teal]>=[/teal][purple]3[/purple][teal])[/teal] [COLOR=darkgoldenrod]alert[/color][teal]([/teal]c[teal]);[/teal]
[teal]}[/teal]
But if you are checking the [tt]arguments.length[/tt], is simple to use a [tt]for[/tt] and a single [tt]if[/tt] instead of 3 [tt]if[/tt]s :
JavaScript:
[b]function[/b] [COLOR=darkgoldenrod]showIt[/color][teal]([/teal]a[teal],[/teal]b[teal],[/teal]c[teal])[/teal]
[teal]{[/teal]
  [b]for[/b] [teal]([/teal][b]var[/b] i[teal]=[/teal][purple]0[/purple][teal],[/teal]l[teal]=[/teal]arguments[teal].[/teal]length[teal];[/teal]i[teal]<[/teal]l[teal];[/teal]i[teal]++)[/teal]
    [COLOR=darkgoldenrod]alert[/color][teal]([/teal]arguments[teal][[/teal]i[teal]]);[/teal]
[teal]}[/teal]
Note that in this case you can just remove the declaration of the formal arguments, if they are not needed for other operations inside the [tt]function[/tt].

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top