Is there a null coalescing operator in Javascript?
For example, in C#, I can do this:
String someString = null;
var whatIWant = someString ?? "Cookies!";
The best approximation I can figure out for Javascript is using the conditional operator:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
Which is sorta icky IMHO. Can I do better?
If
||
as a replacement of C#'s??
isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in
==
versus===
in JavaScript especially when it comes to issues of checking forundefined
and/ornull
.There's a really good article about the difference in two terms here. Basically, understand that if you use
==
instead of===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.
Yes, it is coming soon. See proposal here and implementation status here.
It looks like this:
Example
Currently no support, but the JS-standardization process is working on it: https://github.com/tc39/proposal-optional-chaining
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:
If you were to use the
||
operator, you get the first non-false value:If you use the typical coalesce method, as posted here, you will get
c
, which has the value: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: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?