[javascript] how to check for datatype in node js- specifically for integer

I tried the following to check for the datatype (specifically for integer), but not working.

var i = "5";

if(Number(i) = 'NaN')
{
 console.log('This is not number'));
}

This question is related to javascript node.js

The answer is


You can check your numbers by checking their constructor.

var i = "5";

if( i.constructor !== Number )
{
 console.log('This is not number'));
}

you can try this one isNaN(Number(x)) where x is any thing like string or number


I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

Your logic is correct but you have 2 mistakes apparently everyone missed:

just change if(Number(i) = 'NaN') to if(Number(i) == NaN)

NaN is a constant and you should use double equality signs to compare, a single one is used to assign values to variables.


i have used it in this way and its working fine

quantity=prompt("Please enter the quantity","1");
quantity=parseInt(quantity);
if (!isNaN( quantity ))
{
    totalAmount=itemPrice*quantity;

}
return totalAmount;

_x000D_
_x000D_
var val = ... //the value you want to check_x000D_
if(Number.isNaN(Number(val))){_x000D_
  console.log("This is NOT a number!");_x000D_
}else{_x000D_
  console.log("This IS a number!");_x000D_
}
_x000D_
_x000D_
_x000D_


If you want to know if "1" ou 1 can be casted to a number, you can use this code :

if (isNaN(i*1)) {
     console.log('i is not a number'); 
}