Sunday, April 12, 2009

== vs ===

Here is the msdn documentation

Equality (==, !=)

  • If the types of the two expressions are different, attempt to convert them to string, number, or Boolean.
  • NaN is not equal to anything including itself.
  • Negative zero equals positive zero.
  • null equals both null and undefined.
  • Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.
  • Every other comparison is considered unequal.

Identity (===, !==)

These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal.

Here is some test case writing in Qunit.

test("Equality test", function() { ok(1 == 1 && 'a' == 'a' && 1 == '1' && 0 == false && '' == false); ok(null == null, "null equals to null"); ok(null == undefined, "null equals undefined"); ok(undefined == undefined, "undefined equals undefined"); ok({} != {}, "different objects are unequal"); }); test("Identity test", function() { ok(1 !== "1" && null !== undefined, "must be the same type, not conversion"); });

No comments:

Post a Comment