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

后端 未结 8 1309
情深已故
情深已故 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:32

    Yet another reason for using the typeof-variant: undefined can be redefined.

    undefined = "foo";
    var variable = "foo";
    if (variable === undefined)
      console.log("eh, what?!");
    

    The result of typeof variable cannot.

    Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:

    15.1.1 Value Properties of the Global Object
    [...]
    15.1.1.3 undefined
    The value of undefined is undefined (see 8.1). This property has the attributes
    { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

    But it still can be shadowed by a local variable:

    (function() {
      var undefined = "foo";
      var variable = "foo";
      if (variable === undefined)
        console.log("eh, what?!");  
    })()
    

    or parameter:

    (function(undefined) {
      var variable = "foo";
      if (variable === undefined)
        console.log("eh, what?!");  
    })("foo")
    

提交回复
热议问题