6

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.

2 Answers 2

5

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.

3
  • Hmm, if adding functions is the only way to go, can I define my own null coalescing operator to ??? What are my choices of symbols if not?
    – Ehryk
    Commented Nov 26, 2015 at 7:45
  • stackoverflow.com/questions/476436/…
    – Ehryk
    Commented Nov 26, 2015 at 7:45
  • @Ehryk you can't define your own operators in JS. See answer update though for an improved function.
    – Alnitak
    Commented Nov 26, 2015 at 8:54
2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.