Last Updated: 17 Nov 2023

   |   

Author: 114.119.133.245

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Last revision Both sides next revision
front-end-tech:javascript:optional-parameters-default-arguments [May 23, 2008 11:54 PM]
dordal
front-end-tech:javascript:optional-parameters-default-arguments [Nov 13, 2023 04:07 PM]
111.225.149.10 removed
Line 1: Line 1:
 += Optional Parameters and Default Arguments =
  
 +JavaScript supports optional parameters and default arguments to functions, but only supports the latter with a bit of a hack.
 +
 +Optional parameters are easy. Just define a function to and then don't pass all the parameters:
 +<code>
 +function testFunction(a,b,c) {
 +   document.write(a + " ");
 +   document.write(b + " ");
 +   document.write(c + " ");
 +}
 +
 +testFunction('foo','bar');   // will print 'foo bar undefined '
 +</code>
 +
 +Of course, your function must handle those undefined parameters. You might want to set defaults for any parameters that are undefined; to do this, just check if they
 +are undefined:
 +<code javascript>
 +function testFunction(a,b,c) {
 +   // this says 'if the type of a is undefined, set it to '', otherwise set it 
 +   // to a (e.g. itself)'
 +   a = (typeof(a) == undefined) ? '' : a;   
 +   b = (typeof(b) == undefined) ? '' : b;     
 +   c = (typeof(b) == undefined) ? '' : c;
 +}
 +</code>
 +
 +One other thing that you can do is check the length (or values) of the ''arguments'' array. The ''arguments'' array is set inside each function, and contains a list of the arguments passed to the function.