RobG said:
eval will convert a number that is a string to a JavaScript 'primitive'
number, e.g.
var x = '5'; // the value of x is type string
x = eval(x); // the value of x is now type number
However, there are occasions where eval() returns `undefined' even though
the passed expression would evaluate to a different value.
However:
var x = '5px';
x = eval(x); // Error: missing ; before statement
eval is a black box, the error messages emanating from it are usually
bizarre
^^^^^^^
That is, if I may say so, VK-ish wording ;-) The error message above, for
example, is not bizarre at all if you understand the language, and how its
tokenizer works (all described in the ECMAScript specifications). AIUI, 5
is considered a NumericLiteral because only `px' is what qualifies as an
Identifier here (which MUST NOT start with a decimal digit according to the
specs), and is therefore considered the statement (produced by `Statement
--> ... --> PrimaryExpression : Identifier'). `5;px', as indicated by the
error message, would not make much sense and could even qualify as being
bizarre, but it is _syntactically correct_; `5px' is _not_.
and useless for debugging.
Quite the contrary. eval() can be used for debugging in combination with
the proprietary `onerror' handler when exception handling with try...catch
is not available. Venkman, and the MS Script Debugger can debug eval()
code quite well.
It has other unwelcome consequences (search the archives) - just don't
use eval.
.... if you can avoid it. As you can (and should) here, by using
x = parseInt(x, 10); // or parseFloat(...)
instead. Which is an appropriate, but still not sufficient answer to
the OP's request "that it also works if 'f
.value' is empty or contains
text." Because NaN to which (the more efficient, but not fully backwards
compatible) `+f.value' evaluates then is hardly useful.
PointedEars