Why is the function argument "x" not set to "undefined" when using "x?"
The following CoffeeScript code :
foo = (x) -> alert("hello") unless x? alert("world") unless y?
compiled for:
var foo; foo = function(x) { if (x == null) { alert("hello"); } if (typeof y === "undefined" || y === null) { return alert("world"); } };
Why is foo
x
not set to undefined
and y
is not?
An undefined check is to throw a ReferenceError exception when you retrieve the value of a nonexistent identifier:
>a == 1 ReferenceError: a is not defined
The compiler can see that the identifier x exists, because this is an argument to the function.
The compiler cannot determine if the identifier y exists, and therefore it is necessary to check if y exists.
// y has never been declared or assigned to >typeof(y) == "undefined" true