How do I use the CoffeeScript existential operator to check some object properties for undefined?

前端 未结 3 1883
面向向阳花
面向向阳花 2020-12-02 15:56

I would like to use the CoffeeScript existential operator to check some object properties for undefined. However, I encountered a little problem.

Code like this:

3条回答
  •  猫巷女王i
    2020-12-02 16:27

    This is a common point of confusion with the existential operator: Sometimes

    x?
    

    compiles to

    typeof test !== "undefined" && test !== null
    

    and other times it just compiles to

    x != null
    

    The two are equivalent, because x != null will be false when x is either null or undefined. So x != null is a more compact way of expressing (x !== undefined && x !== null). The reason the typeof compilation occurs is that the compiler thinks x may not have been defined at all, in which case doing an equality test would trigger ReferenceError: x is not defined.

    In your particular case, test.test may have the value undefined, but you can't get a ReferenceError by referring to an undefined property on an existing object, so the compiler opts for the shorter output.

提交回复
热议问题