89

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.

Jaider
  • 14,268
  • 5
  • 75
  • 82

8 Answers8

163

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

Jaider
  • 14,268
  • 5
  • 75
  • 82
  • The question mark is the way to go. It's in the very first code example block of http://coffeescript.org/ - alert "I knew it!" if elvis? – Jo P Oct 26 '12 at 15:33
  • 58
    Actually it only generated `item != null` – Pencilcheck May 26 '13 at 01:34
  • 13
    @Pencilcheck - that's because the compiler determined that item was defined in your code. (also, great name - though it's tablet check for me now :) This answer also picks up null values which are very different from undefined. It seems like an answer to a different question IMHO – Seth Jul 08 '13 at 18:39
  • 3
    @Seth, yes I get burned by that nuance all the time, which raises the next logical question: does CS offer any syntactical shortcut for the following: MyVariable = MyMethod; if MyVariable?... where MyMethod might return `undefined`? Or must you then resort to `if typeof myVariable isnt 'undefined'`? – neverfox Jul 21 '13 at 01:32
  • 1
    @neverfox the latter as far as I'm aware (undefined type check) - CoffeeScript thinks that null and undefined should be conflated. – Seth Jul 24 '13 at 05:55
  • 7
    @Seth, not really. Non-strict comparisons (`==` and `!=`) actually treat `null` and `undefined` as equal values, so `item != null` actually tests both for `null` and `undefined` at the same time. It does not, if it's written as `item !== null`. – toriningen Aug 07 '14 at 02:06
  • 1
    undefined and null are not handled as same values. undefined value can pass null check. simply use "if not item" – eyurdakul Dec 21 '15 at 09:51
  • 1
    To bring my two cents, I have found out that `if(myVar?) {...}` really translates to `if (typeof myVar !== 'undefined' && myVar !== null) {...}` while if we are checking for an object property, such as `@myVar` or `obj.hisVar` it always translates to `if(this.myVar !== null) {..}` or `if(obj.hisVar !== null) {...}`. To remove the confusion and possible errors I recommend using the [@soundslikeneon](http://stackoverflow.com/a/9929551/598500) solution here. – shadyyx Jan 29 '16 at 14:59
26

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!

soundslikeneon
  • 416
  • 3
  • 4
14

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");
}
Community
  • 1
  • 1
AJP
  • 26,547
  • 23
  • 88
  • 127
  • 3
    this is old coffee script. the `variable?` now only compiles to variable != null – Gambai Oct 07 '16 at 16:29
  • @Gambai are you sure? The website still shows `... !== null` http://coffeescript.org/#try:variable%3F – AJP Oct 08 '16 at 14:04
  • 1
    Yes, the compiler now sometimes omits the **!= undefined** as an optimization because when the variable should be defined somewhere in the code. I say _should_ because the compiler does not always work correctly... – Suzana Jan 27 '17 at 13:17
  • @Suzana_K good to know. I'm sure people coming across this question would like an up to date answer, please feel free to edit mine or post a new answer and I'll link to it from the top of mine. I don't use CoffeeScript anymore after adopting ES6 / TypeScript so I can't update the answer. Actually it looks like Jaider's answer covers it: http://stackoverflow.com/a/10238211/539490 – AJP Jan 27 '17 at 14:02
11
typeof MyVariable isnt "undefined" 

from js2coffee

Jonathan
  • 10,936
  • 8
  • 64
  • 79
9

In addition to Jaider's answer above (I couldn't comment due to insufficient reputation), be careful that it's a different case if it's something inside an object/array:

someArray['key']?

will be converted to:

someArray['key'] != null

Screenshot from js2coffee.org:

js2coffee.org

Community
  • 1
  • 1
LongYC
  • 476
  • 3
  • 13
  • You're checking if the key exists, so this makes sense. If you also need to check if the array exists, try someArray?['key']? – JD Byrnes Jun 27 '16 at 18:56
7

I just use:

if (myVariable)
    //do stuff

As undefined is falsy it will only do stuff if myVariable is not undefined.

You just have to be aware that it will 'do stuff' for values that are 0, "" and null

mbx-mbx
  • 1,765
  • 11
  • 23
3

The cleanest way I've found to assign a variable to an undefined and not-null variable is using unless:

unless ( myVar? )
    myVar = 'val'
fooling
  • 111
  • 2
2

Why not just use the OR idiom?

myVar or 'val'

So, the result will equal myVar, unless it is undefined in which case it will equal 'val'.

l3x
  • 30,760
  • 1
  • 55
  • 36
  • 3
    With this idiom any falsish value will return 'val' instead of whatever it supposed to be — including `''`, `0.0` and `false`. Which is, probably, not unwanted. – toriningen Aug 07 '14 at 02:08