Comparison Operators
JavaScript has the following comparison operators:
<less than<=less than or equal>greater than>=greater than or equal
Strings are compared lexicographically:
console.log("Hello" < "Goodbye"); // false
console.log("Hello" < "Hi"); // true
There are no “strict” versions of comparison operations. So, if you mix types, JavaScript converts the types.
console.log("42" < 5); // false: "42" is converted to the number 42
console.log("" < 5); // true: "" is converted to the number 0
console.log("Hello" < 5); // false: "Hello" is converted to NaN
console.log([2] < 5); // true: [2] is converted to the number 2
console.log([1, 2] < 5); // false: [1, 2] is converted to "1,2"
console.log(true > 2); // false: true is converted to the number 1
There are a few more unexpected behaviors:
console.log(NaN < 1); // false
console.log(NaN > 1); // false
console.log(undefined < 1); // false
console.log(undefined > 1); // false
console.log(null < 1); // true
console.log(null > 1); // false
Here is the logic behind these behaviors:
- When one operand is a string, and the other is a number, the string is converted to a number before comparison.
- When the string is non-numeric, numeric conversion returns
NaN. Comparing withNaNalways returns false.- However,
null,false, and""convert to0. And,trueconverts to the number1.
- However,
- When one operand is an object, and the other is a number, the object is converted to a number before comparison.