[Javascript] sort replace question

Nick Fitzsimons nick at nickfitz.co.uk
Tue Feb 28 11:15:11 CST 2006


> // -----
> var y = 3.5;
> var x = parseFloat(y);
>

And of course that parseFloat is unnecessary since the value contained in
y is already a number. What that line actually does internally is:

var x = parseFloat(y.toString(10));

as parseFloat takes a string value. In fact, it gets even more exciting
than that when you consider that primitive types like strings and numbers
are automatically converted to the object equivalents String and Number as
necessary (and converted back again), meaning it's actually doing:

var x = parseFloat(new Number(y).toString(10));

People could avoid a heck of a lot of problems with JavaScript if they
took the time to understand automatic type conversion, kept track of what
the actual types of their variables were, and were aware of which objects
supported which methods. For example, the problem that started this thread
basically comes down to:

new Number(3.5).replace(".", "_");

which is obviously not going to work, as "replace" is a method of String,
not of Number, and Number has no method called "replace".

In fact this case (invoking a method) is one of the situations where the
automatic type conversion isn't done for you, because it's not possible
for the JS interpreter to know what to convert the operand to; all it
knows is that it was given a number [var y = 3.5;], it converted it to a
Number object because a method was invoked on it [y.replace(".", "_");],
and then it found that the Number object didn't support the method.

Just for fun:

var a = parseFloat(new Number(1.2).toString(16));
var b = parseFloat(new Number(1.2).toString(10));
var c = parseFloat(new Number(1.2).toString(2));

See if you can guess what values that gives to a, b and c before you try
it :-)

Regards,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/




More information about the Javascript mailing list