Consider the following example.
const x = false;
const y = "1";
const z = {};
console.log(x < y); // true
console.log(y < z); // true
console.log(x < z); // false
Since x < y
and y < z
both evaluate to true
, I expected x < z
to evaluate to true
too because I thought <
was transitive. I was wrong. The <
operator in JavaScript is not transitive. Hence, JavaScript values don’t form an ordered set. Not even a partially ordered set.
Anyway, I understand why false < "1"
evaluates to true
. The false
is coerced to 0
and the "1"
is coerced to 1
. What I don’t understand is why "1" < {}
evaluates to true
, and why false < {}
evaluates to false
. Could you explain how these three expressions are evaluated, and how the <
operator works in JavaScript?
3
Answers
In the case of
"1" < {}
, the object{}
is not directly comparable, so JavaScript converts the object to a string using the default toString method.Image of conversion of {} to a string using toString Method
So then comparing
"1" < {}.toString
which gives us true, since when comparing "1" (U+0031) comes before "[" (U+005B) alphabetically. Hence the output will be true.Similarly, for the condition
false < {}
, while comparing an object with a boolean, the value for the object is NaN.And hence
0 < NaN
which evaluates to false.The less than (<) operator returns true if the left operand is less than the right operand, and false otherwise.
Let’s see examples of comparisons different types of values.
String to string comparison
String to number comparison
Comparing Boolean, null, undefined, NaN
Also you must know!
Boolean values true and false are converted to 1 and 0 respectively.
null is converted to 0.
undefined is converted to NaN.
Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values.
I hope, helped you. I picked up answer from here
JS tries to compare as numbers if any of the operands is numerish (boolean, number, date), if that fails (for example a string cannot be converted to a number or an operand is an object), it compares as strings.
For objects
toString()
method is used to convert an object to a string so if you provide a numeric string you can actually make an object comparable as a number, theNumerish
example shows how you can change result of the previous comparing a boolean with an object.Moreover an object can implement
valueOf()
method and return actual number.In that case the comparison will be tried as numeric. The
Numeric
example shows that.