wubbewubbewubbe
wubbewubbewubbe

Reputation: 741

looking for alternative way to do isNaN test

I'm looking for an alternative way to do an isNaN test

My original code looked like this. The code works, but I noticed that num1 changes type, which is ugly

// example 1: num1 changes type

num1 = parseInt(str1, 10);
if isNaN(num1){num1=-1;}

I changed it to this, but this one uses duplicate code

// example 2: duplicate code

if (isNaN(parseInt(str1,10))){num1=-1;}
else {num1=parseInt(str1,10);}

At first I was thinking about adding an extra variable to store parseInt(str1,10) but that variable will change type, too and is therefore in effect the same as example 1.

Is there an alternative to example 1 or 2?


by changes type I mean this

console.log(typeof(isNaN("123"))); // boolean 
console.log(typeof(isNaN("abc"))); // boolean 

console.log(typeof(parseInt("123", 10))); // number 
console.log(typeof(parseInt("abc", 10))); // number 

.

console.log(typeof(Number("123"))); // number
console.log(typeof(Number("abc"))); // number

console.log(Number("123")); // 123
console.log(Number("abc")); // NaN

Upvotes: 0

Views: 1447

Answers (1)

Pointy
Pointy

Reputation: 413757

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 );

Upvotes: 4

Related Questions