Can I set variables to undefined or pass undefined as an argument?

后端 未结 10 1885
北荒
北荒 2020-11-30 15:53

I’m a bit confused about JavaScript’s undefined and null values.

What does if (!testvar) actually do? Does it test for u

10条回答
  •  自闭症患者
    2020-11-30 16:46

    The basic difference is that undefined and null represent different concepts.

    If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

    var a;
    
    a == null; // This is true
    a == undefined; // This is true;
    a === undefined; // This is true;
    

    However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

    var b = null;
    b == null; // This is true
    b == undefined; // This is true;
    b === undefined; // This is false;
    

    Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

    This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

    http://en.wikipedia.org/wiki/Undefined_value

提交回复
热议问题