[thelist] javascript comparison

liorean liorean at f2o.org
Thu Oct 30 09:35:06 CST 2003


Jeff Howden wrote:
>>From: Rob Smith
>>My javascript test is testing supposedly numerical
>>values as strings, when they should be compared by
>>actual value.
> yup, javascript is typeless, so it thinks numbers are strings, unless
> explicitly told otherwise.

Not exactly. JavaScript is dynamically, weakly typed; but it is not 
typeless. An easy way to demonstrate this is to compare the results of 
2+2 (4), and '2'+2 (22). JavaScript simply tries to preserve data. What 
is really happening in this case, is that he's entered a number into the 
form field, and is trying to read the form field value. The value 
property of form fields is considered to be a string, so that's why he 
has to make it into a number first. This can be done by many ways, 
multiplication by 1, substraction by 0, using the Number object, or 
using one of parseFloat or parseInt.

>> Is there a way I can cast values in javascript?
> not really, but you can force the parser to treat a value as a number using
> the parseInt() function.

You can use the host objects for type casting, but there is seldom any 
reason for that, as functions such as parseInt generally provide better 
ways of doing it.
-- 
liorean <mailto:liorean at user.bip.net>

ViewStyles, ViewScripts, ToggleStyles and GraphicsInfo bookmarklets and 
Theme Switcher, Cookies Handler scripts:
<http://liorean.web-graphics.com/>



More information about the thelist mailing list