How to tell if a variable is of type Number in JavaScript?


In javascript, because there is no declaration of variable types like Integer , String , Boolean , etc., it is a difficult task to know what type of value you are dealing with in a given variable.

So, to make my code consistent, I'd like to know how to go about checking whether a variable is a Numeral or not.

How is this possible?


It's simple to know if a variable is Numero or not as there is a native Javascript operator that says the type of your variable, which would be the typeof operator, there are some types of Javascript variables known:

typeof 0;    //number
typeof 1;    //number
typeof 0.5;  //number

typeof '1';  //string
typeof 'a';  //string
typeof " ";  //string

typeof true; //boolean
typeof false;//boolean

typeof [1,2]         //object
typeof {"obj":[2,3]} //object
typeof {"obj":"3"}   //object

typeof function(){alert('foo')} //function

typeof a    //undefined -- note que nao declarei a
typeof null //null é um object(wtf)

So here is an example of a function that checks if the type is number

function isNumber(val){
  return typeof val === "number"

Testing all the values ​​that I exemplified above, you will see that only those with type number that I commented out will return true .

We can also modify "number" by another type to create a function that checks if it's a string for example, or if it's boolean , it's that simple.

In fact, it's a disadvantage, depending on your point of view, that in Javascript you don't need to declare the type and variable before using it.

Scroll to Top