Apr 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");
});

If you want writing a "if (condition)" statement, you should use identity compare, and you can also default boolean conversion in javascript. You can write "if (variable_name)" or "if (variable_name)". Javascript treat false, null, undefined, "" (emtpy string), 0, NaN as falsy value, all other values are truthy, including "0", and "false". If you want to explicitly to convert a variable into boolean type, you can use !!variable_name statement, but you shouldn't use "if (!!variable_name) " statement. Here is some example