JavaScript undefined replaced with null

前端 未结 4 1254
后悔当初
后悔当初 2021-02-08 14:44

In JavaScript undefined can be reassigned, so it is often advised to create a self executing function that assures undefined is actually undefined. As an alternati

4条回答
  •  时光取名叫无心
    2021-02-08 15:32

    Because JavaScript has both values. And while other languages may only have nil/null JavaScript grew up with undefined being the "unknown value" while null is clearly a known value to represent nothing.

    Compare var x where x is undefined because no value has been assigned and var y = null where y is null. It was set to something -- a sentential representing "nothing". This core fundamental usage of undefined vs null in JavaScript runs very deep and other cases include:

    1. A missing (or delete'd) property also yield undefined and not null (it would result in null only if null had been assigned).
    2. Unassigned function parameters are undefined.
    3. undefined returned from standard functions like getElementById. See comments.

    Thus, in Javascript, it is often more correct to use undefined and not null. They both represent different things. A library that tries to fight this is fighting JavaScript.

    Happy coding.


    Personally, in almost all cases I avoid an explicit check for undefined or null. I believe that in most -- but not all -- cases all false values should be equivalent and that it is the callers responsibility to conform to the public contract stated.

    Because of this belief I would consider the comparison x == null on the verge of trying to guard too much and yet too little, but in the case of catching null or undefined, it works, as pointed out. Go start a trend ;-)

提交回复
热议问题