3 ms·
Yet, there is still a value x such that x != x and x !== x. That value is NaN. If true equality matters, use a helper function: function equal(a, b) {
by spicyj 15y ago
Yet, there is still a value x such that x != x and x !== x.
That value is NaN.
If true equality matters, use a helper function:
function equal(a, b) {
if (a === b)
return true ;
if (isNaN(a) && isNaN(b))
return true ;
return false
}
People keep repeating this as a strangeness of JavaScript, whereas in fact this is standard floating-point behavior, the same as you'll see in any other language (C, Java, Python, really everything). In JavaScript, you almost always just want a === b, not a function that checks for NaN.
- chc 15y agoI think it's because you're more likely to encounter NaN in JavaScript due to the lack of real integers (er, should I say true integers? Everything is floating-point, anyway).
- asynchrony 15y agoSince NaN != NaN you could also do (a === b) || ((a != a) && (b != b))
- underwater 15y agoI don't know why you'd use a != a instead of isNaN(a). The former hides what you're doing. Though treating two NaN values as equal doesn't even make sense in the first place.