First, I would suggest that parseInt()
isn't the best choice. For example:
var x = parseInt("123hello world how are you today?", 10);
will set "x" to 123 and simply ignore the trailing garbage.
You could set up a functional way to do this, if you really wanted to avoid the intermediate temporary value:
function ifNumeric( s, f ) {
s = +s;
if (!isNaN(s)) f(s);
}
ifNumeric( someString, function( n ) { /* whatever, with "n" being a number */ } );
but that seems a little extreme. But anyway note that in that example the +
operator is used to coerce the value of the variable to the "number" type. You could alternatively use the "Number" constructor, but not as a constructor:
var numeric = Number( someString );
Either of those will give you a NaN
if the string isn't a completely valid number without trailing garbage.
edit — if you just want a safe "give me a number" converter:
function toNumber( value, ifGarbage ) {
value = +value;
return isNaN(value) ? ifGarbage : value;
}
var num1 = toNumber( str1, -1 );