In javascript to check if a variable was never created, we just do
if (typeof MyVariable !== "undefined"){ ... }
I was wonder how I do that in coffeescript?... I try something like
if (MyVariable?false){ ... }
but this check if MyVariable
is a function if so that will call MyVariable(false) if not that will call void(0) or something like that.
Finally I found this easy way to do it:
if (MyVariable?){ ... }
that will generate:
if (typeof MyVariable !== "undefined" && MyVariable !== null){ ... }
UPDATE 04/07/2014 Demo Link
First, to answer your question:
if typeof myVariable isnt 'undefined' then # do stuff
Magrangs' solution will work in most cases, except when you need to distinguish between undefined and false (for example, if myVariable can be true, false or undefined).
And just to point out, you shouldn't be wrapping your conditions in parentheses, and you shouldn't be using curly braces.
The then
keyword can be used if everything is on the same line, otherwise use indentation to indicate what code is inside of the condition.
if something # this is inside the if-statement # this is back outside of the if-statement
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With