Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript Undefined

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.

like image 553
Jaider Avatar asked Mar 29 '12 16:03

Jaider


2 Answers

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

enter image description here

like image 111
Jaider Avatar answered Oct 02 '22 22:10

Jaider


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!

like image 39
soundslikeneon Avatar answered Oct 02 '22 23:10

soundslikeneon