Speed of comparing to null vs undefined in JavaScript

后端 未结 4 1935
生来不讨喜
生来不讨喜 2021-02-05 01:23

I have just run a very simple JavaScript performance test (don\'t ask why). The test declares a variable, but doesn\'t assign anything to it:

var x;

4条回答
  •  囚心锁ツ
    2021-02-05 01:52

    You're comparing against the lookup of a variable called undefined (which returns an undefined value), so it's not doing what you were intending.

    There are ways to check whether a variable is undefined. As the other posters have mentioned, typeof x === 'undefined' is one. (There's probably another possibility that is something like hasOwnProperty('x') executed on the global object, but that doesn't check the scope chain.)

提交回复
热议问题