variable === undefined vs. typeof variable === “undefined”

后端 未结 8 1238
情深已故
情深已故 2020-11-22 14:43

The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

  • Global Variables: typeof variable === "undefined&
8条回答
  •  死守一世寂寞
    2020-11-22 15:12

    I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.

    I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.] However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.

    For example, the following is used in IE for parsing XML:

    var x = new ActiveXObject("Microsoft.XMLDOM");
    

    To check whether it has a loadXML method safely:

    typeof x.loadXML === "undefined"; // Returns false
    

    On the other hand:

    x.loadXML === undefined; // Throws an error
    

    UPDATE

    Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to @LinusKleen for reminding me. For example:

    typeof someUndeclaredVariable; // "undefined"
    someUndeclaredVariable === undefined; // throws a ReferenceError
    

    Bottom line: always use the typeof check.

提交回复
热议问题