JavaScript isNaN() Function returning unexpected result

Smith
Smith
None
2568 Points
74 Posts

I am using isNan() method to check if a string is a valid number as:

var str='';
if(isNaN(str)){
  console.log('Not a Number!');
}else{
  console.log('Number!');
}

But it show 'Number'.

Views: 9812
Total Answered: 2
Total Marked As Answer: 1
Posted On: 25-Sep-2017 04:50

Share:   fb twitter linkedin
Answers
ethanm
ethanm
Member
24 Points
2 Posts
         

See isNaN() method behaviour as:

isNaN(123) //false
isNaN(-1.23) //false
isNaN(5-2) //false
isNaN(0) //false
isNaN('123') //false
isNaN('Hello') //true
isNaN('2017/12/12') //true
isNaN('') //false
isNaN(true) //false
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
Posted On: 25-Sep-2017 05:11
Brian
Brian
Moderator
2232 Points
14 Posts
         

The purpose of 'isNaN' is not really to test if something is not a number, but you can use it to test if something is the number NaN (since NaN===NaN returns false in JavaScript you can't use equality).

You should use 'typeof' instead, and then isNaN as:

if((typeof str) === 'number' && !isNaN(str))
Posted On: 26-Sep-2017 02:08
 Log In to Chat