2

This coffeescript...

if x? isnt '' then console.log x

Compiles to this javascript...

if ((typeof x !== "undefined" && x !== null) !== '') {
  console.log(x);
}

Where typeof x is checked against undefined

However, if I use x in the current scope, coffeescript explicitly declares it at the to of the scope, and then does not bother checking for undefined...

This coffeescript...

x = y.z
if x? isnt '' then console.log x

Compiles to this javascript...

var x;

x = y.z;

if ((x != null) !== '') {
  console.log(x);
}

It is possible that x ends up being undefined if y.z is undefined. Why does coffeescript not feel the need to check for undefined in the if statement?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237

1 Answers1

2

Let's start with the more obvious case, the second example:

The compiler knows that var x is declared, even if it is not defined, so all it needs to do is check that the value isn't null or undefined which can be done with x != null.

However, this isn't the case in the first example. x hasn't been declared anywhere, so trying x != null would actually throw a ReferenceError, however typeof x will return a value (and if x is in fact not null or undefined all will be will in the universe.

phenomnomnominal
  • 5,427
  • 1
  • 30
  • 48