Comparison Operators
Javascript has the following comparison operators:
<
less than<=
less than or equal>
greater than>=
greater than or equal
Use these to compare numbers with numbers or strings with strings.
Strings are compared lexicographically:
console.log("Hello" < "Goodbye"); console.log("Hello" < "Hi");
There are no "strict" versions of comparison operations. So, if you mix types, JavaScript will go about converting types!
console.log("42" < 5); // "42" is converted to the number 42 console.log("" < 5); // "" is converted to the number 0 console.log("Hello" < 5); // "Hello" is converted to NaN console.log([2] < 5); // [2] is converted to the number 2 console.log([1, 2] < 5); // [1, 2] is converted to "1,2" console.log(true > 2); // true is converted to the number 1
More madness:
console.log(NaN < 1); console.log(NaN > 1); console.log(undefined < 1); console.log(undefined > 1); console.log(null < 1); console.log(null > 1);
The logic(!) behind the madness:
- 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 withNaN
always returns false.- However,
null
,false
, and empty string convert to0
. And,true
converts 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.
Avoid mixed-type comparisons!