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)
5 Answers 5
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.
5 Comments
undefined ?) but it sure looks best for "skipping optional parameters".undefined is not an option to call these methods. One needs introduce an if to choose the right parameter list length wtfShort 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 undefinedevaluates to"undefined"typeof nullevaluates 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
- While
undefinedalso 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.
Comments
By using ES6 javascript!
function myfunc(x = 1, y = 2, z = 6) {
console.log(x);
console.log(y);
console.log(z);
}
myfunc(5) //Output: 5 2 6
myfunc(3, undefined, 8) //Output: 3 2 8
// Better way!
function myfunc(x = 1, y = 2, z = 6) {
console.log(x);
console.log(y);
console.log(z);
}
// skip y argument using: ...[,] and it's mean to undefine
// 1 argument for ...[,] 2 arguments for ...[,,] and so on.....
myfunc(7, ...[, ], 4); //Output: 7 2 4
4 Comments
...[,] syntax? Do you mind sharing any docs?[,] is not even ES6, is just the syntax to create an empty spot in an array. try typing [,,,] in console, it responds with (3) [empty × 3] meaning an array of length 3 but no values, which is different from 3 undefined values. in fact, you can create empty spots in the middle of an array, like [1,,2,3] == [1, empty, 2, 3]. destructuring (ES6 feature) an array with empty spots, just gets "converted" to passing undefined values X times. why? because "reading" the value of an empty spot will give you undefined. for example, [0,,2][1] === undefinedJust 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)
6 Comments
goog.net.XhrIo.send() works please rephrase the question.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.==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...There is another option that avoids writing specific undefined values in every parameter that one wants to skip. In ES6 one can make use of the Spread syntax with an array and use it as the parameters of the function call. If you don't specify a value, it will be taken as undefined by default (take into account that this could be less readable than using undefined values).
const test = (a = 'A', b = 'B', c = 'C') => {
console.log(`${a} / ${b} / ${c}`);
};
test(); // A / B / C
test(...[, 'X', 'Y']); // A / X / Y
test(...['X', , 'Y']); // X / B / Y
test(...[, , 'X']); // A / B / X
And this occurs because:
const array = [ , , , 'A'];
console.log(array); // [undefined, undefined, undefined, 'A']