开发者

undefined and null

undefined === null => false
undefined == null => true
  1. I have thought about the reason of undefined == null and found out only one case:

    if(document.getElementById() == null) ....
    

    Is there any other reason to make (undefined === null) == false ?

  2. Is the开发者_StackOverflow中文版re any other examples of use === - operation in javascript?


Is there any other reason to make (undefined === null) == false ?

They are not equal so the Strict Equality Comparison Algorithm considers them to be false.

Is there any other examples of use === - operation in javascript?

The === gives the most predictable result. I only use == when I have a specific purpose for type coercion. (See Abstract Equality Comparison Algorithm.)


null and undefined are two different concepts. undefined is the lack of value (if you define a variable with var without initializing it, it doesn't contain null, but undefined), while with null the variable exists and is initialized with the value null, which is a special type of value.

JavaScript equality operator is broken though, Crockford found out that it lacks transitivity and for this reason suggests to use always the strict equality (===). Consider this table published in Javascript the good parts:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true


=== is strict equal.

Undefined and null are not the same thing.

== uses type coercion.

null and undefined coerce to each other.


Type coercion (using the == operator) can lead to undesired or unexpected results. After following all the talks I could find of Douglas Crockford on the net (mostly Yahoo video) I got used to using === all te time. Given my default usage of the strict equal operator I would be more interested in type coercion javascript use cases ;~) nowadays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜