Reputation: 147
The last days I read how NaN always compares false even with itself and how to compare stuff when NaN may occur, and now I made a JS that compares two NaN true. WTF? Or did I compare 'NaN' strings?
http://www.bksys.at/bernhard/JS-NaN-compare-true.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radioactivity calculator</title>
</head>
<body>
<form name="form1">
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
x: <input type="text" name="x"><br>
</form>
<script type="text/javascript">
document.form1.a.value=Math.sqrt(-1);
document.form1.b.value=(1/0)/(1/0);
document.form1.x.value=(document.form1.a.value==document.form1.b.value);
</script>
</body>
</html>
Upvotes: 1
Views: 776
Reputation: 128791
You are indeed comparing the string "NaN"
against another string "NaN"
, which equates to true. The value
held in text input
elements is always pulled as a String type.
A simple way to resolve this is to prefix your values with the Unary Plus (+
) operator to convert them to integer values (you can drop those brackets, too):
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
document.form1.a.value = Math.sqrt(-1);
document.form1.b.value = (1/0) / (1/0);
document.form1.x.value = +document.form1.a.value == +document.form1.b.value;
<form name="form1">
a: <input type="text" name="a" size="20" value="a"><br>
b: <input type="text" name="b" size="20" value="b"><br>
x: <input type="text" name="x" size="20" value="x"><br>
</form>
Note: As RobG pointed out in his comment below it's important to note here that converting the string value "NaN"
to an integer with the Unary Plus operator converts it directly to NaN
because the string cannot be replicated as a numeric value. The same would happen if both of your input
elements contained the value "Foo"
- or even contained two completely different non-numeric string values. Whilst this solution does work, it may yield undesired results if you are to extend this code to handle non-numeric values as well.
Upvotes: 3
Reputation: 4742
NaN
is a special value in JavaScript. It doesn't even equal itself (also a quick way to test):
var a = parseInt('seven');
if (a == a) {
alert("a == a");
} else {
alert("a != a"); // This will happen
}
if (a == 'NaN') {
// Won't happen
} else {
alert("NaN is not equal to the string 'NaN'"); // Here
}
Upvotes: -1
Reputation: 2417
This is a JavaScript gotcha ;)
The proper way to compare NaN is to use the isNaN
method.
var a = 'a' + 5; //NaN
if (isNaN(a)) {
//do something
}
Upvotes: 0