December 5, 1999 - Identity 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:
NaNis not equal to anything including itself.
nullequals both
nulland
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:
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