This answer is for an older version of coffeescript. See Jaider's answer above if you want a more up to date answer (as of July 2014)
This coffeescript does what you want I think:
if not MyVariable?
MyVariable = "assign a value"
Which produces:
if (!(typeof MyVariable !== "undefined" && MyVariable !== null)) {
MyVariable = "assign a value";
}
N.b. if you make an assignment to MyVariable
first, even if you set MyVariable
to undefined as in this code, then this compiles to:
if (!(MyVariable != null)) {
MyVariable = "assign a value";
}
I believe this works because the !=
used by CoffeeScripts Existential Operator
(the question mark) coerces undefined
to be equal to null
.
p.s. Can you actually get if (MyVariable?false){ ... }
to work? It doesn't compile for me unless there's a space between the existential operator and false i.e. MyVariable? false
which then makes CoffeeScript check it like a function because of the false
which it thinks is a parameter for your MyVariable
, for example:
if MyVariable? false
alert "Would have attempted to call MyVariable as a function"
else
alert "but didn't call MyVariable as it wasn't a function"
Produces:
if (typeof MyVariable === "function" ? MyVariable(false) : void 0) {
alert("Would have attempted to call MyVariable as a function");
} else {
alert("but didn't call MyVariable as it wasn't a function");
}