skip to Main Content

Javascript has the === and !== operators for a strict isEquals test. Is there any way to do this on the other comparison operators? If not, what is the idiomatic way to do that check? For example, with the following 6 comparisons (the last four don’t exist):

  • Equals: 1 === "1"
  • Does not equal: 1 !== "1"
  • Greater than or equal to: 1 >== "1" (doesn’t exist)
  • Less than or equal to: 1 <== "1" (doesn’t exist)
  • Greater than: 1 > "1" (but without cast)
  • Less than: 1 < "1" (but without cast)

2

Answers


  1. If you want to check whether two values have the same type and the one is greater/lesser than the other, test that explicitly:

    typeof a === typeof b && a < b
    typeof a === typeof b && a <= b
    typeof a === typeof b && a >= b
    typeof a === typeof b && a > b
    

    There are no builtin operators for this, and they are rarely necessary anyway. In idiomatic code, it is clear which type of value a variable has, so you won’t need to check it.

    Login or Signup to reply.
  2. I don’t think there is a strict version of those operators, but you could improvise with type checks first. ex:

    a = 1;
    b = "2";
    console.log(a < b);
    console.log(typeof a == typeof b && a < b);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search