null vs. undefined and their behaviour in JavaScript

后端 未结 4 824
春和景丽
春和景丽 2020-12-14 08:20

So after a big argument/debate/discussion on the implementation of null and undefined in javascript I\'d like somebody to explain the reasoning behind the implementation and

4条回答
  •  孤街浪徒
    2020-12-14 08:54

    They are best thought of as completely different objects used for different purposes:

    null is used for "has no value." It is used pretty rarely by the language, but often used by the host environment to signify "no value." For example, document.getElementById returns null for nonexistant elements. Similarly, the IE-only property onreadystatechange for HTMLScriptElements is set to null, not undefined, to signify that though the property exists, it's currently not set. It is generally good practice to use null in your own code, instead of undefined, and leave undefined for the following cases:

    undefined is used for "isn't even set or doesn't even exist." It is the "default" in many cases, e.g. accessing an undefined property (like onreadystatechange for HTMLScriptElement in non-IE browsers), the default return value from methods without return statements, the default value of function parameters when the function is called with fewer arguments than it declares, and the like.

    In this way, it's useful to think of null as a "valid value," just one signifying something special. Whereas undefined is more of a language-level thing.

    Sure, there are some edge cases where these reasonings don't entirely hold; those are mostly for legacy reasons. But there is a difference, and it's one that makes some deal of sense.


    As for your pain points in particular, they mostly arise from the evil of the == operator or type coercion:

    • null == undefined: don't use the == operator, because it essentially is a mess of backward-compatibility rules that seemed intuitive at the time.
    • null + 1 === 1 vs. undefined + 1 === NaN: the + operator does type coercion to Number before evaluating. And null coerces to 0 (+null === 0) whereas undefined coerces to NaN (isNaN(+undefined) === true).
    • if (!null), if (null), null == false: if evaluates the "truthiness" or "falsiness" of its argument, which has nothing to do with the mess of rules for ==. null is falsy, and !null is truthy, but the rules for == don't let null == false.

提交回复
热议问题