0

Is there a way in Javascript to make strict comparison operations other than the one allowed with '===', i.e., a strict '<', '>', '<=' and '>='?

The code below using '<' performs a weak operation between a string and an integer. I would like to know if this could be achieved as done with '==='.

let a = '9';
let b = 10;
if (a < b) {
    console.log('Success');
}  // Prints 'Success'

Thanks!

Alejandro
  • 37
  • 9
  • Familiarize yourself with how [IsLessThan](//tc39.es/ecma262/#sec-islessthan) works. How do you expect a “strict” `<` to work, precisely? – Sebastian Simon Oct 26 '22 at 23:31
  • I would expect it to return some kind of falsy value, since one of the values is not a number. I will look into that method, thank you! – Alejandro Oct 26 '22 at 23:32
  • This isn't possible in JavaScript, but with TypeScript, you'll get a compiler error: https://tsplay.dev/mAr1XW - Consider switching to TypeScript :) – kelsny Oct 26 '22 at 23:39
  • Excellent, good to know that. I'm yet to learn TS, will sooner or later do. Thanks :). – Alejandro Oct 26 '22 at 23:42

1 Answers1

0

No, there is no such set of operators. Also they would violate the usual expectation that (a < b) != (a >= b) / (a <= b) != (a > b)1.

Of course you can build this yourself by writing

if (typeof a == typeof b && a < b) …

1: this expectation doesn't actually hold for the normal operators either, there are values like NaN that violate it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375