Comparison operators (JavaScript)

Comparison operators compare two values and yield a logical (boolean) result.

The following table describes the comparison operators.

Operator Description
expr1 == expr2 Equal. Returns true if expr1 and expr2 are equal. Conversion occurs if the operands are of different types.
expr1 != expr2 Not equal. Returns true if expr1 and expr2 are not equal. Type conversion occurs as necessary.
expr1 === expr2 Strict equal. Returns true if expr1 and expr2 are of the same type, and are equal.
expr1 !== expr2 Strict not equal. Returns true if expr1 and expr2 are of different types, or are of the same type but not equal.
expr1 > expr2 Greater than. Returns true if expr1 is greater than expr2. Type conversion occurs as necessary.
expr1 >= expr2 Greater than or equal to. Returns true if expr1 is greater than or equal to expr2. Type conversion occurs as necessary.
expr1 < expr2 Less than. Returns true if expr1 is less than expr2. Type conversion occurs as necessary.
expr1 <= expr2 Less than or equal to. Returns true if expr1 is less than or equal to expr2. Type conversion occurs as necessary.

Usage

Operand comparisons occur as follows:
  • Two strings are equal if they have the same sequence of characters and same length. Strings are greater or less than each other depending on the Unicode values of their characters in sequence.
  • Two numbers are equal if they have the same numeric value. NaN is not equal to anything, including NaN. Positive and negative zero are equal.
  • Two objects are equal if they refer to the same Object.
  • Two boolean values are equal if they are both true or false.
  • The null and undefined types are equal.
Type conversion occurs as follows:
  • For comparison with numbers, strings are converted to numbers (values of typeNumber ) if possible. If the conversion result is NaN, the comparison is false.
  • For comparison with boolean values, the number 0 (positive or negative, integer or floating point) is false and all other numbers are true, the empty string is false and all other strings are true, null is false, and undefined is false.
  • For comparison with numbers and strings, objects convert to numbers or strings using the valueOf and toString methods of the objects. If the conversion fails, a runtime error occurs.

Examples

This example exercises the various comparison operators on numbers.
function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var n = 9;

p("n == 9: " + (n == 9)); // true
p("n != 9 : " + (n != 9)); // false
p("n == \"9\" : " + (n == "9")); // true
p("n != \"9\" : " + (n != "9")); // false
p("n === \"9\" : " + (n === "9")); // false
p("n !== \"9\" : " + (n !== "9")); // true
p("n > 9: " + (n > 9)); // false
p("n >= 9: " + (n >= 9)); // true
p("n < 9: " + (n < 9)); // false
p("n <= 9: " + (n <= 9)); // true
p("n > \"9\" : " + (n > "9")); // false
p("n >= \"9\" : " + (n >= "9")); // true
p("n < \"9\" : " + (n < "9")); // false
p("n <= \"9\" : " + (n <= "9")); // true