Andr
Andr

Reputation: 627

Comparing with NaN in Javascript

I have met this strange issue.

enter image description here

Why is so?! Should it be so?

Upvotes: 1

Views: 1980

Answers (4)

Marc B
Marc B

Reputation: 360762

NaN is like an SQL null. It is never equal to anything, including itself. That's why there's the special case function isNaN() to safely test for NaN's presence.

Upvotes: 2

JohnB
JohnB

Reputation: 13723

The reason behind this is that the rules of mathematics should be preserved. Otherwise, one would have x == x + 1 if x is NaN, which is not a true relationship for any other value of x.

Upvotes: 5

neu-rah
neu-rah

Reputation: 1693

that's why we use

isNaN(x)

it seems that x is a NaN object and it does not compare equal to another

Upvotes: 3

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

From the MDN docs for isNaN:

Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.

use isNaN instead.

Upvotes: 12

Related Questions