-3

I’m having trouble with the isNaN function is JavaScript. I have a variable, trc, which I know is not a number, but I want my code to be able to tell. Unfortunately, isNaN isn’t detecting that it’s not a number, yet when I use an alert to show the value of the variable, it is indeed not a number.

trc = parseInt(getCookie("trc"));
cnn = parseInt(getCookie("cnn"));
klove = parseInt(getCookie("klove"));
if (isNaN(trc)) {
  trc = 0;
}
if (getCookie("trc") == undefined) {
  trc = 0;
} else {
  trc = parseInt(getCookie("trc"));
}
alert(trc);

BTW, I have a separate function, getCookie(), that I made myself to get the value of a cookie.

Tushar
  • 85,780
  • 21
  • 159
  • 179
ColorCodin
  • 101
  • 2
  • 11
  • `parseInt` isn't executing as getCookie is undefined. – Ian Aug 21 '15 at 13:31
  • 5
    The `isNaN()` function means, "is the parameter the `NaN` value?" not "is the parameter not a number". – Pointy Aug 21 '15 at 13:31
  • Also note that it's possible to get to that `alert()` after setting `trc` to the cookie value without an intermediate `isNaN()` test. If the cookie value is not `undefined`, then the second `if` statement will set `trc` to the result of passing the cookie value to `parseInt()`, which may return `NaN`. – Pointy Aug 21 '15 at 13:33
  • You'll have to provide some sample data with which it fails. The function is probably working just fine as it's supposed to, you simply have the wrong expectations for your input. – deceze Aug 21 '15 at 13:35
  • Thanks, decease. You and Kamil are right. I fixed it by checking if trc > -1, since the way my program runs it will always be 0 or greater. Of course, if trc isn’t a number it won’t be less than 0. Thanks for the help everyone! – ColorCodin Aug 21 '15 at 16:54

1 Answers1

0

You should check value of trc before. If trc is null, then isNaN(null) return false.

Edit: parseInt method doesn't return null value, but trc can be modified by external code - therefore I recommend using namespaces e.g:

var namespace = namespace || {};
namespace.trc = .....