December 5, 1999 - Identity Operators | WebReference

December 5, 1999 - Identity Operators

Yehuda Shiran December 5, 1999
Identity Operators
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

JavaScript's standard equality operators (== and !=) check if two expressions are equal (or not equal). If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. 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. Here are a few more rules:
NaN is not equal to anything including itself.
  • Negative zero equals positive zero.
  • null equals both null and undefined.

    Every other comparison is considered unequal. JavaScript's identity (strict equality) operators (=== and !==) behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal. Here are a few examples:

    "3" == 3 // true
    "3" === 3 // false
    1 == true // true
    1 === true // false
    "1" == true // true
    "1" === true // false

    The problem with JavaScript's identity operators is that they are only supported by some browsers:

    Browser:IE4IE5N2N3N4/C4 (JS1.2)N4.06/C4.5 (JS1.3)
    Type Conversion (== and !=)yesyesyesyesnoyes
    Available (=== and !==)yesyesnononoyes

    IE = Microsoft Internet Explorer
    N = Netscape Navigator (standalone)
    C = Netscape Communicator

    We can use the typeof operator to achieve the same results:

    function seq(x, y) { // ===
      return ((typeof(x) == typeof(y)) && (x == y)); // AND
    }
    function sneq(x, y) { // ===
      return ((typeof(x) != typeof(y)) || (x != y)); // OR
    }
    seq("3", 3) // false
    sneq("3", 3) // true
    seq(1, true) // false
    sneq(1, true) // true
    seq("1", true) // false
    sneq("1", true) // true
    seq(5, 5) // true
    sneq(5, 5) // false