views:

1177

answers:

5

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?

+1  A: 
whatIWant === null
Gumbo
I don't think that's exactly what I want.. i'll clarify my question.
Daniel Schaffer
+2  A: 

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 for undefined and/or null.

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.

Tom
One things that bugged me about that article (and Jash) is, an undefined window.hello property being evaluated to null for some reason. It should be undefined instead. Try it Firefox error console and see for yourself.
Ates Goral
+45  A: 

The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

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:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
Ates Goral
perfect, thank you!
Daniel Schaffer
@Ates, can you modify your answer with a warning that zeros and empty strings are treated the same as null or undefined values by the || operator?
Daniel Schaffer
@Daniel Schaffer - I agree that some clarification would help. Added.
Ates Goral
First class answer... if I could +1 again, I would. Thanks!
Daniel Schaffer
Strings like "false", "undefined", "null", "0", "empty", "deleted" are all true since they are non-empty strings.
some
exactly what i was looking for. looks like i'm about a year behind :)
Jason
@Ates Goral: +1 and Array.prototype.forEach = Array.prototype.forEach || function(... is WHAT?
Marco Demajo
@Marco Demaio: That's saying: "if forEach is already is defined, use that, otherwise, use this function".
Ates Goral
@Ates Goral: so this trick should work also in this case, I'm asking because on Mozilla website they use a normal if(!Array.prototype.forEach) Array.prototype.forEach = function(...
Marco Demajo
@Marco Demaio: Actually, the "normal" way is better. The shorthand you mentioned is too terse and involves an unnecessary reassignment (assuming the runtime doesn't optimize it out).
Ates Goral
This needs to be clarified. "" is not null but is consider falsey. So if you are checking a value for null and it happens to be "" it won't correctly pass this test.
ScottKoon
Justin Johnson
A: 

beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript. 1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object
  1. Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); } // alerts

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

farzad
Actually, null is a value. It's a special value of type Object. A variable being set to null means it contains data, the data being a reference to the null object. A variable can be defined with value undefined in your code. This is not the same as the variable not being declared.
Ates Goral
The actual difference between a variable being declared or not: alert(window.test)/*undefined*/; alert("test" in window)/*false*/; window.test = undefined; alert(window.test)/*undefined*/; alert("test" in window)/*true*/; for (var p in window) {/*p can be "test"*/}
Ates Goral
+2  A: 

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:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');
sth
alert(null || '') still alerts an empty string, and I think I actually like that alert('' || 'blah') alerts blah rather than an empty string - good to know though! (+1)
Daniel Schaffer