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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With