Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coffee script testing if not defined

Tags:

coffeescript

according to the coffee script site

console.log(s) if s?

should generate

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

But what is showing up in my browser is

  if (s != null) {
      return console.log(s);
  }

Using coffee-script-source (1.6.2), coffee-rails (3.2.2), rails-backbone (0.7.2), rails (3.2.13)

Here is my coffee script function. any thoughts on why I am not getting what coffee script site says I should??

window.p = (s) ->
    console.log(s) if s?
like image 468
peter cooke Avatar asked Sep 05 '13 02:09

peter cooke


People also ask

How do you check for undefined in CoffeeScript?

if (typeof MyVariable !== "undefined" && MyVariable !==

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.


2 Answers

If you say just a bare:

console.log(s) if s?

then you will indeed get the JavaScript you're expecting (demo):

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

However, if s is a known variable such as here:

f = (s) -> console.log(s) if s?

then you'll get (demo):

if (s != null) {
  //...
}

for the s? test.

So why the difference? In the first case, CoffeeScript cannot guarantee that there is an s variable in existence anywhere so it must do a typeof s check in order to avoid a ReferenceError exception.

However, if s is known to exist because it is a function parameter or has been assigned to as a local variable (so that CoffeeScript will produce a var s), then you don't need the typeof s check since you cannot, in this case, get a ReferenceError.

That leaves us with s !== null versus s != null. Dropping down to non-strict inequality (s != null) allows you to check if s is undefined or null with a single comparison. When you check typeof s !== "undefined", you wrapping the undefined test in with the "is there an s variable" check and a strict s !== null test is all that you need to check for null.

like image 139
mu is too short Avatar answered Oct 21 '22 17:10

mu is too short


You're right,

(s) -> console.log(s) if s?

console.log(x) if x?

compiles to

(function(s) {
  if (s != null) {
    return console.log(s);
  }
});

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

It looks like the CoffeeScript compiler is optimizing the Javascript a little bit for you, because in the case of a function argument like this, typeof s will never be undefined as s is defined right there in the function signature, even if its value is null.

like image 2
nicolaskruchten Avatar answered Oct 21 '22 19:10

nicolaskruchten