[thelist] javascript comparison

webcoder at cox.net webcoder at cox.net
Thu Oct 30 07:53:41 CST 2003

> Is there a way I can cast values in javascript?

You've already gotten some excellent replies to this, but I must disagree with Jason when he gave you this advice for checking for NaN.
>if (parseInt(bid.previousbid.value) == NaN || parseInt(bid.nextbid.value)== NaN)

Checking for NaN is absolutely correct, but that way won't work.  When NaN is compared to anything, including itself, it returns false.  So, the comparison ==NaN will never return true, even if one of those values is not a number.

Instead, you should use the isNaN() function to check for NaN.  Something like this:
if (isNaN(parseInt(bid.previousbid.value) ) || isNaN(parseInt(bid.nextbid.value)))

If you don't use isNaN(), you won't find NaN.

Jeff Howden, as usual, is spot on with his advice to use the optional second argument of the parseInt() function.  If a value begins with 0, and there is no second argument, parseInt() does convert it to octal.  That can be very difficult to spot, so Jeff's advice could save you hours of frustration.

Lastly, I'll mention another method of achieving the same goal.  Using simple mathematics on the value will cause javascript to treat it as an integer.  So, subtract zero from it, or multiply it by one.

So, this would work:

if ( isNaN(bid.previousbid.value*1 ) || isNaN(bid.nextbid.value*1) )

as would this
if ( isNaN(bid.previousbid.value-0 ) || isNaN(bid.nextbid.value-0) )

best regards,


More information about the thelist mailing list