Nobody has mentioned in here the potential for NaN
, which--to me--is also a null-ish value. So, I thought I'd add my two-cents.
For the given code:
var a,
b = null,
c = parseInt('Not a number'),
d = 0,
e = '',
f = 1
;
If you were to use the ||
operator, you get the first non-false value:
var result = a || b || c || d || e || f; // result === 1
If you use the typical coalesce method, as posted here, you will get c
, which has the value: NaN
var result = coalesce(a,b,c,d,e,f); // result.toString() === 'NaN'
Neither of these seem right to me. In my own little world of coalesce logic, which may differ from your world, I consider undefined, null, and NaN as all being "null-ish". So, I would expect to get back d
(zero) from the coalesce method.
If anyone's brain works like mine, and you want to exclude NaN
, then this method will accomplish that:
function coalesce() {
var i, undefined, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg !== null && arg !== undefined
&& (typeof arg !== 'number' || arg.toString() !== 'NaN') ) {
return arg;
}
}
return null;
}
For those who want the code as short as possible, and don't mind a little lack of clarity, you can also use this as suggested by @impinball. This takes advantage of the fact that NaN is never equal to NaN. You can read up more on that here: Why is NaN not equal to NaN?
function coalesce() {
var i, arg;
for( i=0; i < arguments.length; i++ ) {
arg = arguments[i];
if( arg != null && arg === arg ) { //arg === arg is false for NaN
return arg;
}
}
return null;
}
x ?? y
syntax is now in stage 1 proposal status - nullish coalescing – Aprillionx ?? y
) and optional chaining operator (user.address?.street
) are now both Stage 4. Here's a good description about what that means: 2ality.com/2015/11/tc39-process.html#stage-4%3A-finished . – Mass Dot Net