Speed of comparing to null vs undefined in JavaScript

后端 未结 4 1936
生来不讨喜
生来不讨喜 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:35

    null is a reserved keyword which cannot be overriden, so when you are doing a comparison against null, all you have to do is a single comparison.

    However, when you are checking against undefined, the engine must do a type lookup and then a comparison, meaning that it is actually slightly more demanding.


    If you need to actually check to see if something is undefined, you should use

    if(typeof notSet == "undefined"){ }
    

    Proof

    Try it... and set something to null in your JavaScript console.

    null = "will error";
    // Errors with --> ReferenceError: invalid assignment left-hand side
    

    However, if you try and do it with undefined, it won't error. That is not to say that you can override undefined, because you can't, but that undefined is its own primitive type.

    The only real similarity between null and undefined, is that they can both be coerced into a boolean false.

    0 讨论(0)
  • 2021-02-05 01:41

    I recently discovered that this:

     if (typeof this._minLat === 'undefined') {
       this._minLat = Math.min(...this.points.map(point => point.lat));
     }
     return this._minLat;
    

    seems to be many times faster than this:

     return  this._minLat || Math.min(...this.points.map(point => point.lat));    
    
    0 讨论(0)
  • 2021-02-05 01:42

    if i think well, they are not the same. so you can't use null instead of undefined.

    typeof !== "undefined" vs. != null

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题