I just tried the following in a node.js console:
> 5 <= "5"
true
Which means that the =
part of the <=
is treated the same way ==
is, not ===
. Which made me immediately try <==
hoping it would do what you would hope it would. But it doesn't exist.
Then I tried the following:
> 5 < "6"
true
Then I started to observe even stranger behaviour:
> 5 < [6]
true
Which brings up a more important question: are there type-safe equivalents to <
, >
, <=
, and >=
?
I just tried the following in a node.js console:
> 5 <= "5"
true
Which means that the =
part of the <=
is treated the same way ==
is, not ===
. Which made me immediately try <==
hoping it would do what you would hope it would. But it doesn't exist.
Then I tried the following:
> 5 < "6"
true
Then I started to observe even stranger behaviour:
> 5 < [6]
true
Which brings up a more important question: are there type-safe equivalents to <
, >
, <=
, and >=
?
- 5 I edited your title. Your previous title was wondering into "Hey, could a language designer tell me why this feature isn't here?" and this is more, "How do I do type-safe parison in JavaScript? – George Stocker Commented May 28, 2014 at 2:00
- Long story short: no there is not (built-in). – Felix Kling Commented May 28, 2014 at 2:01
2 Answers
Reset to default 8No, but it can be handled by correct use of existing language features to type check.
Comparison is ideally two state logic. Either a<b
or it is not. The problem is that bining type checking with parison changes two state logic into three state (true/false/inparable). To return one of three outes would no longer be a simple Boolean.
A pre-check on types can already be implemented with typeof
or instanceOf
If parisons must be type-appropriate, and there is no code written to deal with mismatches, then an error can be thrown to stop execution as in the following example:
if (typeof(a) !== typeof(b)) {
throw `type mismatch in some_function(), types: ${typeof(a)}, ${typeof(b)}`;
}
// now the next operation is "safe"
if (a <= b) {
do_something();
} else {
do_the_other_thing();
}
Later when there is error handling code, you can replace the throw or keep the throw and use try/catch.
No, there's nothing built in to do so.
Consider:
// I invented ~ as the non type coercion operator
5 <~ 6
5 <~ '6'
Both of these return false, but the return values don't really mean the same thing. In the second case, it likely wouldn't have even pared the values.