Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')); } 
like image 838
Prem Avatar asked Sep 27 '13 10:09

Prem


People also ask

How do you determine the datatype of a variable in node JS?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

How do you check if a number is an integer in JS?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you check if a variable is a certain type in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.


2 Answers

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.

like image 195
Endre Simo Avatar answered Oct 03 '22 23:10

Endre Simo


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; 
like image 37
Mayur Gupta Avatar answered Oct 04 '22 00:10

Mayur Gupta