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.

Ehryk
  • 1,930
  • 2
  • 27
  • 47

2 Answers2

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 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 Nov 26 '15 at 07:45
  • http://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript – Ehryk Nov 26 '15 at 07:45
  • @Ehryk you can't define your own operators in JS. See answer update though for an improved function. – Alnitak Nov 26 '15 at 08:54
1

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.

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35