How to Pass Optional Parameters to a Function

How to pass optional parameters while omitting some other optional parameters?

As specified in the documentation, use undefined:

export interface INotificationService {
error(message: string, title?: string, autoHideAfter? : number);
}

class X {
error(message: string, title?: string, autoHideAfter?: number) {
console.log(message, title, autoHideAfter);
}
}

new X().error("hi there", undefined, 1000);

Playground link.

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

Is there a better way to do optional function parameters in JavaScript?

Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative

if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }

Or an alternative idiom:

optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;

Use whichever idiom communicates the intent best to you!

Is there a way to pass optional parameters through two functions?

One thing that you could do is use the **kwargs syntax to allow for any keyword arguments to be passed through, and then just raise errors if there are any extra keywords that don't mean anything (or alternatively, just cleanly ignore them, though that confuses users in case they make a typo and no error occurs). In the case of cleanly ignoring them:

def foo(x1, **kwargs):
if "opt" in kwargs:
bar(kwargs["opt"])
else:
bar()

Basically, the **kwargs lets you pass in any keyword arguments like foo(opt = 3) and puts them all in a dict. The downside to this is that you cannot call it like foo(3). If you want to go by placement arguments instead of keyword arguments, you can do *args which gives a tuple of the arguments, but then you are unable to call it with the keyword specified. You cannot do both, unfortunately.

How do I define a function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

JavaScript function with optional parameters

A good way to do this would be to use an object for all of the arguments. Something like:

function plotChart(options) {
// Set defaults
options.chart_type = options.chart_type || '1';

// Check if each required option is set
// Whatever is used by the data
}

Then when the function is called:

plotChart({
data: 'some data',
xlabel: 'some xlabel',
ylabel: 'some ylabel',
chart_type: '5' // This is optional
});

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
// function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
b = b || 0;

// b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy.
Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

Default optional parameter in Swift function

Optionals and default parameters are two different things.

An Optional is a variable that can be nil, that's it.

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).



Related Topics



Leave a reply



Submit