JavaScript Reference ยท Operators
JavaScript comparison operators
Reference for JavaScript comparison operators: strict and loose equality, inequality, and relational operators, with type coercion rules and NaN pitfalls.
Comparison operators compare two values and return a boolean. There are two families: equality (===, !==, ==, !=) and relational (<, >, <=, >=).
Strict equality (===) never converts types: values of different types are never equal. Loose equality (==) converts operands first and has surprising rules, so most style guides recommend === everywhere, with == null as the one common exception.
a === b a !== b a == b a != b a < b a > b a <= b a >= b
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
x === y // strict equality x !== y // strict inequality x == y // loose equality x != y // loose inequality x < y // less than x > y // greater than x <= y // less than or equal x >= y // greater than or equal
Return value: true or false.
Rules in short:
| Case | Result |
|---|---|
Different types with === |
always false |
NaN compared with anything (including itself) using ===, ==, <, >, <=, >= |
false |
Two objects with == or === |
true only if they are the same object |
null == undefined |
true; neither equals any other value with == |
Number vs string with ==, < etc. |
the string is converted to a number |
Two strings with < etc. |
compared by UTF-16 code units, left to right |
Object vs primitive with == or < |
the object is converted to a primitive first (valueOf, then toString) |
Exceptions: comparing a Symbol with < or > against a number throws a TypeError (conversion to a number is not allowed). Equality never throws.
Usage notes
- Prefer
===and!==. Use== nullonly when you deliberately want to test for bothnullandundefined. - Never compare against
NaNwith an operator. UseNumber.isNaN(x)orObject.is(x, NaN). - Objects compare by identity. To compare arrays or objects by content, compare their elements yourself, or compare serialized forms when that is safe.
- Strings compare by code unit, not by language rules. Use
localeCompare()orIntl.Collatorfor human-friendly ordering. - Mixed
nullcomparisons are odd:null >= 0andnull <= 0are bothtrue, yetnull == 0isfalse, because relational operators convertnullto0but==does not. - Floating point:
0.1 + 0.2 === 0.3isfalse; compare with a small tolerance. - Chained comparisons do not work:
1 < x < 10compiles but evaluates(1 < x) < 10. Write1 < x && x < 10.
Browser support
Supported in every browser and runtime.