Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  28] [ 1]  / answers: 1 / hits: 127028  / 11 Years ago, fri, september 27, 2013, 12:00:00

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

More From » node.js

 Answers
7

I think of two ways to test for the type of a value:



Method 1:



You can use the isNaN javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN. That's why if you console.log out the result, you will be surprised that the code:



if (isNaN(i)) {
console.log('This is not number');
}


will not return anything. For this reason a better alternative would be the method 2.



Method 2:



You may use javascript typeof method to test the type of a variable or value



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


Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.



A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.


[#75390] Thursday, September 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theodore

Total Points: 318
Total Questions: 97
Total Answers: 119

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
;