Is There a Better Way to Do Optional Function Parameters in JavaScript

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!

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.

Javascript : optional parameters in function

Any unfilled argument will be undefined.

concatenate(a, c) is equivalent to concatenate(a, b). You cannot pass the third parameter without passing the second; but you can pass undefined (or null, I suppose) explicitly: concatenate(a, undefined, c).

In the function, you can check for undefined and replace with a default value.

Alternately, you can use an object argument to imitate keyword arguments: concatenate({a: a, c: c}).

Skipping optional function parameters in JavaScript

Solution:

goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})

You should use undefined instead of optional parameter you want to skip, because this 100% simulates the default value for optional parameters in JavaScript.

Small example:

myfunc(param);

//is equivalent to

myfunc(param, undefined, undefined, undefined);

Strong recommendation: use JSON if you have a lot of parameters, and you can have optional parameters in the middle of the parameters list. Look how this is done in jQuery.

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
});

In JavaScript, how can I create a function with an optional parameter?

The first google response I discovered:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions

I haven't seen any instances where a question mark is used to alert a caller to an optional parameter. While it's done in other languages, I don't think it's necessary in javascript.

In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.

javascript: optional first argument in function

You have to decide as which parameter you want to treat a single argument. You cannot treat it as both, content and options.

I see two possibilities:

  1. Either change the order of your arguments, i.e. function(options, content)
  2. Check whether options is defined:

    function(content, options) {
    if(typeof options === "undefined") {
    options = content;
    content = null;
    }
    //action
    }

    But then you have to document properly, what happens if you only pass one argument to the function, as this is not immediately clear by looking at the signature.

Handling optional parameters in javascript

You can know how many arguments were passed to your function and you can check if your second argument is a function or not:

function getData (id, parameters, callback) {
if (arguments.length == 2) { // if only two arguments were supplied
if (Object.prototype.toString.call(parameters) == "[object Function]") {
callback = parameters;
}
}
//...
}

You can also use the arguments object in this way:

function getData (/*id, parameters, callback*/) {
var id = arguments[0], parameters, callback;

if (arguments.length == 2) { // only two arguments supplied
if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
callback = arguments[1]; // if is a function, set as 'callback'
} else {
parameters = arguments[1]; // if not a function, set as 'parameters'
}
} else if (arguments.length == 3) { // three arguments supplied
parameters = arguments[1];
callback = arguments[2];
}
//...
}

If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.

Javascript - function with optional parameters as object?

Are you looking for something like:

function loadMap(args) { 
args = args || {};
args.latitude = args.latitude || "X.XXX";
args.longitude = args.longitude || "Y.YYY";
alert(args.latitude);
alert(args.longitude);
};

loadMap({latitude:"custom_latitude"});


Related Topics



Leave a reply



Submit