Last Updated: 17 Nov 2023
|
Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous 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 17, 2023 04:00 PM] 114.119.133.245 old revision restored (Oct 7, 2023 07:10 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 '' |