Reputation: 1988
I'm looking for a way to do undefined coalescing in javascript with booleans. I'm used to doing the following, for, say, positive integers:
var x = i1 || i2 || i3 || i4;
This is a 'slick' way, but is not what I'm after. I'm looking for the equivalent of ??
in C#.
var b1 = undefined;
var b2 = null;
var b3 = false;
var b4 = true;
var x = b1 || b2 || b3 || b4; //x == true (b4)
However, I want the above to 'stop' on false (coalesce on undefined or null, but NOT false). The application I'm doing this for is similar to the following:
var threshold = argv[2] ?? process.env.threshold ?? config.threshold ?? 0.3;
var verbose = isTrue(argv[3] ?? process.env.verbose ?? config.verbose ?? false);
I'm looking for a slick way do to this, similar to the ||
operator, not:
var verbose = false;
if (config.verbose !== undefined && config.verbose !== null) verbose = isTrue(config.verbose);
if (process.env.verbose !== undefined && process.env.verbose !== null) verbose = isTrue(process.env.verbose);
if (argv[3] !== undefined && argv[3] !== null) verbose = isTrue(argv[3]);
Similarly, I'd want a '0' threshold to be accepted for the threshold, and any undefined or null values skipped.
Upvotes: 7
Views: 5310
Reputation: 5694
As of December 7th, 2022:
Nullish coalescing operator (??
) is supported by the browsers used by roughly 94% of users. Polyfills for older browsers are available in popular bundlers.
The operator is also available on Node.js as of version 14.
Upvotes: 2
Reputation: 339985
The slickest way (without adding extra functions) that I can think of is:
var x = [b1, b2, b3, b4].find(x => x !== null && x !== undefined);
If this is to be used over and over, define a function that does all the work for you:
function coalesce() {
return [].find.call(arguments, x => x !== null && x !== undefined);
}
var x = coalesce(b1, b2, b3, b4);
NB: ES2015 syntax used and functionality used above! It'd be trivial to rewrite in "old" syntax and shim the Array.prototype.any
function for older browsers.
Also note that without native support for a coalescing operator that all of the parameters above will be evaluated - you lose the advantage of the short circuiting of ||
or ??
wherein the right hand expression isn't evaluated if the left hand expression is returned.
Upvotes: 5