Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type checking in javascript

How can I check if a variable is currently an integer type? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)

like image 405
sova Avatar asked Dec 22 '10 23:12

sova


People also ask

What does JavaScript use instead of and != To include type checking?

The subset does not include the comma operator, the bitwise operators, or the ++ and — operators. It also disallows == and != because of the type conversion they perform, requiring use of === and !== instead.

What is typeof for a class in JavaScript?

Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.

What is typeof in JavaScript example?

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.

Can typeof be called on typeof in JavaScript?

Using typeof could never generate an error. However, with the addition of block-scoped let and const , using typeof on let and const variables (or using typeof on a class ) in a block before they are declared will throw a ReferenceError .


2 Answers

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo 

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10) 
like image 100
Quentin Avatar answered Sep 21 '22 19:09

Quentin


These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3 js> Number.isInteger(x) true js> var y = 3.1 js> Number.isInteger(y) false 
like image 39
dat Avatar answered Sep 20 '22 19:09

dat