Misha Moroshko
Misha Moroshko

Reputation: 171341

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

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?

Upvotes: 6

Views: 148

Answers (1)

user240515
user240515

Reputation: 3207

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

Upvotes: 9

Related Questions