Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there type-safe equivalents to the comparison operators in JavaScript?

Tags:

javascript

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 >=?

like image 447
Sahand Avatar asked May 28 '14 01:05

Sahand


1 Answers

No, 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 combining type checking with comparison changes two state logic into three state (true/false/incomparable). To return one of three outcomes would no longer be a simple Boolean.

A pre-check on types can already be implemented with typeof or instanceOf

If comparisons 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.

like image 60
Paul Avatar answered Sep 21 '22 10:09

Paul