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?
Best Answer
Update
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is
null
orundefined
, and otherwise returns its left-hand-side operand.Old Answer
Please check compatibility before using it.
The JavaScript equivalent of the C# null coalescing operator (
??
) is using a logical OR (||
):There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
Clarification
Regardless of the type of the first operand, if casting it to a Boolean results in
false
, the assignment will use the second operand. Beware of all the cases below:This means: