How does JavaScript evaluate operations more or less?

In particular, operations greater or equal.

Logically, n >= k should be equal to n > k || n == k n > k || n == k , but that doesn't seem to be the case.

Why is this so:

 var d1 = new Date(2018, 1, 16); var d2 = new Date(2018, 1, 16); console.log(d1 > d2); console.log(d1 < d2); console.log(d1 == d2); console.log(d1 >= d2); console.log(d1 <= d2); 

produces false , false , false , true , true ?

+8
javascript
source share
1 answer
  console.log(d1 > d2); console.log(d1 < d2); 

First, they convert them to numbers, and then compare them. Since they are at the same time, they got the same number, so it is not more or less than the other.

  console.log(d1 == d2); 

This checks if the date references match. But they are not like two different objects.

  console.log(d1 >= d2); console.log(d1 <= d2); 

They compare them by numbers, but also for equality. If you do:

  console.log(+d1 === +d2); 

you see that they are equal in the quantity that they represent.

Link: == <=


TL; DR: use === and manually convert types to prevent this odd behavior ...

+8
source share

All Articles