Why doesn't JavaScript have strict greater/less than comparison operators?
While JavaScript's type-strict comparison operators (===
, !==
) are nice, it doesn't have corresponding strict comparisons for greater/less than.
var x = 10;
x <= 20; // true
x <= '20'; // true
x <== 20; // true (or would be, if JS had such an operator)
x <== '20'; // false (ditto)
Why not? I ask this question fully expecting the answer to be "uh, because it doesn't", but I'm asking anyway, in case there's an interesting and/or disheartening historical reason for such operators being omitted.
Solution 1:
I can only guess-
Ifa === b
is false, thena !== b
is true. always.
But, this implication wouldn't hold for <==
Ifx <== 20
is false, we cannot infer the result of
x >== 20
because it might have been false due to type check, or the relation check.
I think that's slightly confusing, although there's plenty of things in the language that are much worse (type coercion in general, to name one).
However, I think a strict <
or >
would behave consistently.
Solution 2:
Since a === b
is a shorthand for typeof a == typeof b && a == b
, you can use this expansion for inequalities: typeof a == typeof b && a <= b
for example.
Solution 3:
I'm not sure there is an answer to your question. My guess is, the intended use is for comparing numbers to strings (and maybe booleans). It actually works for those cases, as the non-strict equality operator does. Anything else is subject to arbitrary type coercion rules anyway. What would be the "correct" output of [] < {}
? false
? Maybe undefined
? Note that the types don't even need to be different, ({foo: 1}) < {bar : 2}
also doesn't make any sense.
In my opinion, they (Brendan Eich, and later the ECMAScript committee) just decided to trust that the developers would only compare things that make sense comparing. Or didn't even consider that developers would try crazy comparisons. Creating extra operators for comparison would only clutter the language. And don't forget comparisons are not the only pitfalls when dealing with type coercion, there's also addition, subtraction, etc. So I guess they just decided to be true to their decision of allowing operations between different types. They thought that would help people when they know what they're doing, but maybe didn't anticipate all the confusion that arose from that.