Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript evaluate greater-than and less-than operations?

Tags:

javascript

More specifically, greater-than-or-equal-to operations.

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

Why is it that this:

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 ?

like image 423
Strikegently Avatar asked Feb 16 '18 19:02

Strikegently


People also ask

How do you do greater than or less than in JavaScript?

In JavaScript they are written like this: Greater/less than: a > b , a < b . Greater/less than or equals: a >= b , a <= b . Equals: a == b , please note the double equality sign == means the equality test, while a single one a = b means an assignment.

How do you do greater than in JavaScript?

The greater than operator ( > ) returns true if the left operand is greater than the right operand, and false otherwise.

What does <= mean in JavaScript?

The less than or equal operator ( <= ) returns true if the left operand is less than or equal to the right operand, and false otherwise.


1 Answers

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

These convert them to numbers first, then compare them. As they are at the same time, they got the same number so one is not bigger or smaller than the other.

 console.log(d1 == d2);

This checks if the date references are the same. But they are not as they are two different objects.

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

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

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

you see that they are equal by the number they represent.

Reference: == <=


TLDR: use === and manually convert types to prevent such odd behaviour...

like image 193
Jonas Wilms Avatar answered Oct 19 '22 22:10

Jonas Wilms