69

Could you please point me to the nice way of skipping optional parameters in JavaScript.

For example, I want to throw away all opt_ parameters here:

goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content, {'Cache-Control': 'no-cache'}, opt_timeoutInterval)
Dan
  • 48,995
  • 35
  • 110
  • 141

3 Answers3

130

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.

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
Dan
  • 48,995
  • 35
  • 110
  • 141
  • 1
    +1. I don't know what this does exactly (same as `undefined` ?) but it sure looks best for "skipping optional parameters". – Thilo Dec 02 '11 at 23:01
  • I have found that you can never be sure what to pass instead of "skipped" parameter. Undefined? Null? 0? Empty string? Empty object? Array? **If behaviour of omittting the parameter in not docummented, or there is no default parameter, you are in great trouble**. You can't sleep well if you update the external library. Only god and maybe library developer can know what will happen if you pass anything unexpected instead of the required parameter. Generaly if this behaviour is not documented, the bugs are on you – Dan Apr 03 '13 at 18:09
  • THis still works in 2017 on the latest google chrome version so I'm upvoting. – Anonymous Mar 30 '17 at 10:29
  • 1
    Hi, this works well, unless the function uses arguments.length. See this example: argl = function() { return arguments.length; }   argl(1) => 1   argl(1, undefined, undefined) => 3   argl(1, undefined, 2) => 3 – MarekJ47 Aug 31 '17 at 12:51
  • The npm module oracledb makes heavy use of arguments.length. Mostly to decide if a callback is given. Unfortunately, `undefined` is not an option to call these methods. One needs introduce an `if` to choose the right parameter list length *wtf* – Newlukai May 02 '19 at 13:27
31

Short answer

The safest bet is undefined, and should work almost ubiquitously. Ultimately, though, you cannot trick the function being called into thinking you truly omitted a parameter.

If you find yourself leaning towards using null just because it's shorter, consider declaring a variable named _ as a nice shorthand for undefined:

(function() { // First line of every script file
    "use strict";
    var _ = undefined; // For shorthand
    // ...
    aFunction(a, _, c);
    // ...
})(); // Last line of every script

Details

First, know that:

  • typeof undefined evaluates to "undefined"
  • typeof null evaluates to "object"

So suppose a function takes an argument that it expects to be of type "number". If you provide null as a value, you're giving it an "object". The semantics are off.1

As developers continue to write increasingly robust javascript code, there's an increasing chance that the functions you call explicitly check a parameter's value for undefined as opposed to the classic if (aParam) {...}. You'll be on shaky ground if you continue to use null interchangeably with undefined just because they both happen to coerce to false.

Be aware, though, that it is in fact possible for a function to tell if a parameter was actually omitted (versus being set to undefined):

f(undefined); // Second param omitted
function f(a, b) {
    // Both a and b will evaluate to undefined when used in an expression
    console.log(a); // undefined
    console.log(b); // undefined
    // But...
    console.log("0" in arguments); // true
    console.log("1" in arguments); // false
}

Footnotes

  1. While undefined also isn't of type "number", it's whole job is to be a type that isn't really a type. That's why it's the value assumed by uninitialized variables, and the default return value for functions.
Doug Paul
  • 1,073
  • 10
  • 15
4

Just pass null as parameter value.

Added: you also can skip all consequent optional parameters after the last that you want to pass real value (in this case you may skip opt_timeoutInterval parameter at all)

Yuriy Rozhovetskiy
  • 21,488
  • 4
  • 32
  • 62
  • 3
    Are you quite sure there is no ` === undefined` checking inside? – Dan Dec 02 '11 at 12:25
  • @Dan, you phrased your question as a generic JavaScript question with that code as an example. If you need help specifically with how `goog.net.XhrIo.send()` works please rephrase the question. – nnnnnn Dec 02 '11 at 12:30
  • 1
    Thank you very much @nnnnnn, but this is really a *generic* JavaScript question and the answer should work in *any* case. If there is no generic solution, please post it in your answer. – Dan Dec 02 '11 at 12:34
  • 1
    @Dan, I can't be sure, how developer who's implement the `goog.net.XhrIo.send` method check for optional parameters. He's may check for `param === undefined` or `typeof param === "undefined"` or `param === null` or event just `if(param)`. But when you pass null value it's a sign that you're realizing that this parameter is optional and explicitelyy tell that you don't want to pass any meaning value. – Yuriy Rozhovetskiy Dec 02 '11 at 12:41
  • 1
    You could pass undefined instead of null, it could be more likely to work in more cases, but I'm not sure there's an answer that will work in _any_ case. If I were writing a function with optional params I'd probably check with `==null` to allow for undefined or null (unless null is a legit value for some reason), but I might check the length of the `arguments` object, and I've seen other code that checked with `===null` so... – nnnnnn Dec 02 '11 at 12:51
  • once null is evaluated it may cause the function to fail, thus, `undefined` should be included – auerbachb Dec 04 '20 at 22:05