DEV Community

Kush
Kush

Posted on • Updated on

NaN is neither greater than nor less than any value

Have you ever been in a situation where you're expecting something and you get something unexpected in return?
Well, I'm not talking about "the mysteries of life" but "the mysteries of Javascript".

Consider we've something like this below:

let x = 9;
let y = "11";
let z = "14";

Enter fullscreen mode Exit fullscreen mode
x < y; // true
y < z; // true
z < x; // false
Enter fullscreen mode Exit fullscreen mode

x < y
So, what's exactly happening here is, if either of the values or both are strings i.e, when x < y, then both the values are coerced to be numbers and a typical numerical comparison happens.

y < z
But if both the values in the < comparison are strings, the comparison is made lexicographically same as the order you find in any dictionary.

Let's look at another case when one of the values can't be made into a valid number.

let x = 11;
let y = 'z';
Enter fullscreen mode Exit fullscreen mode
x < y; // false
x > y; // false
x == y; // false
Enter fullscreen mode Exit fullscreen mode

Most of us should be confused, how all the three comparisons be false? but it's okay to be confused here. The thing to catch here is value y is being coerced to 'Not a Number' (NaN) in the equality comparisons and NaN is neither greater than nor less than any other value.

Ref: YDKJS

Top comments (0)