Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript Existential Operator and this

Tags:

coffeescript

I noticed something a little odd with the CoffeeScript compilier and was wondering if this was correct behavior or not. If it is correct I'm curious why there is a difference..

Given the following CoffeeScript:

if @myVar?
  alert myVar

I was expecting it to compile to JavaScript like this:

if (typeof this.myVar !== "undefined" && this.myVar !== null) {
  alert(myVar);
}

But instead what the CoffeeScript compiler outputs is this:

if (this.myVar != null) {
  alert(myVar);
}

If I don't reference this (or any other parent object), the CoffeeScript compiles as I would expect.

Is this the correct behavior? If so, why does it work different when using this?

Edit:

To add a little more clarification. This doesn't happen with only this, but any other properties of objects. For instance, if I were replace the above CoffeeScript with what's below it still would compile with only "!= null"...

if myVar.myProp?
  alert myVar
like image 610
Jason L. Avatar asked Apr 03 '12 11:04

Jason L.


People also ask

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

How do you write a CoffeeScript?

In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below.


1 Answers

In the case of:

myVar = 10
if myVar?
  alert myVar

Coffeescript compiler is able to see that myVar is really defined in the first line, so it can omit typeof myVar !== "undefined" check.

if (myVar !== null) {
  alert(myVar);
}

But in this case:

if myVar?
  alert myVar

compiler can't guarantee that myVar is actually defined, so extra check is required:

if (typeof myVar !== "undefined" && myVar !== null) {
  alert(myVar);
}

So, the answer is: Coffeescript compiler tries to be smart to produce efficient code.

EDIT The way Coffeescript deals with properties is also correct: this.prop will return undefined if property is not defined. != will convert it to null. That is why we don't need additional check.
In few words:

  • accessing undefined variable throws exception -- need to check typeof
  • accessing undefined property returns undefined -- just != is enough
like image 82
max taldykin Avatar answered Sep 28 '22 17:09

max taldykin