Javascript Reference
Categories: Operators

javascript Operators ==

@March 15, 2008, 1:22 a.m.
== Firefox/Netscape/NN 2 IE 3 ECMA 1  

  

The equality operator compares two operand values and returns a Boolean result. The behavior of this operator differs with the version of JavaScript specified for the script element. If the language attribute is set to JavaScript or JavaScript1.1, some operands are automatically converted as shown in the following table.

Left operand Right operand Description
Object reference Object reference Compare evaluation of object references.
Any data type Boolean Convert Boolean operand to a number (1 for true; 0 for false) and compare against other operand.
Object reference String Convert object to string (via toString( )) and compare strings.
String Number Convert string to a number and compare numeric values.
 

Navigator 4 and later observes slightly different value conversions for determining equality when you explicitly set the script element to language="JavaScript1.2". The browser is more literal about equality, meaning that no automatic data conversions are performed. Therefore, whereas the expression:

123 == "123"
 

evaluates to true in most situations due to automatic data type conversion, the expression evaluates to false in Navigator 4 and later but only in statements belonging to explicitly JavaScript 1.2 scripts. Because newer DOM and XHTML standards don't provide a place to specify scripting language versions, you should avoid these special-case situations. If your scripts require tests for absolute equality of operands, use the newer === identity operator instead. For typical value equality testing, the standard equality operators work perfectly well.

 

Regardless of version, if you wish to compare the values of objects (for example, comparing strings explicitly generated with the new String( ) constructor), you should compare the values derived from methods such as toString( ) or valueOf( ).

 
Example
 
if (n == m) {
    ...
}

Powered by Linode.