Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the function argument "x" is not checked for "undefined" when using "x?"?

Tags:

coffeescript

The following CoffeeScript code:

foo = (x) ->
  alert("hello") unless x?
  alert("world") unless y?

is compiled to:

var foo;

foo = function(x) {
  if (x == null) {
    alert("hello");
  }
  if (typeof y === "undefined" || y === null) {
    return alert("world");
  }
};

Why is foo's argument x is not checked for undefined, while y is?

like image 382
Misha Moroshko Avatar asked May 16 '12 05:05

Misha Moroshko


1 Answers

The undefined check is to prevent the ReferenceError exception that's thrown when you retrieve the value of a nonexistent identifier:

>a == 1
ReferenceError: a is not defined

The compiler can see that the x identifier exists, because it's the function argument.

The compiler cannot tell whether the y identifier exists, and the check to see whether y exists is therefore needed.

// y has never been declared or assigned to
>typeof(y) == "undefined"
true
like image 152
user240515 Avatar answered Sep 22 '22 12:09

user240515