Question: What is the proper way to define a function in JavaScript that takes optional parameters?
For example:
function myFunc(optionVar1) { if(optionVar1 == undefined) { ... } else { ... } } myFunc('10'); // valid function call myFunc(); // also a valid function call
Is it proper to use a ?
mark like Ruby in the function declaration like so to denote optional parameters:
function myFunc(optionVar1?) {...} // <--- notice the ? mark
Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.
Use a question mark to set an optional parameter in a function in TypeScript, e.g. function sum(a: number, b?: number) {} . If set to optional, the parameter can have a type of undefined or the specified type, because unspecified parameters get the value undefined . Copied!
There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined
so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:
function myfunc(someParam) { if (someParam === undefined) { someParam = 10; } ... }
Also you can access the parameters programmatically using the arguments
property.
Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.
Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.
You can set defaults like
function throw_cat(dist){ dist = typeof dist=='undefined' ? 20 : dist; //OR dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default //etc... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With