Last Updated: 17 Nov 2023
|
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision Next revision Both sides next revision | ||
front-end-tech:javascript:optional-parameters-default-arguments [May 23, 2008 11:53 PM] dordal created |
front-end-tech:javascript:optional-parameters-default-arguments [Oct 14, 2023 04:43 AM] dordal old revision restored (Nov 21, 2020 10:39 PM) |
||
---|---|---|---|
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: | ||
+ | < | ||
+ | function testFunction(a, | ||
+ | | ||
+ | | ||
+ | | ||
+ | } | ||
+ | |||
+ | testFunction(' | ||
+ | </ | ||
+ | |||
+ | 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, | ||
+ | // this says 'if the type of a is undefined, set it to '', | ||
+ | // to a (e.g. itself)' | ||
+ | a = (typeof(a) == undefined) ? '' | ||
+ | b = (typeof(b) == undefined) ? '' | ||
+ | c = (typeof(b) == undefined) ? '' | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | One other thing that you can do is check the length (or values) of the '' |