It is simple to know if a variable is Numero
or not because 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 whether the type is number
function isNumber(val){
return typeof val === "number"
}
Testing all the values that I have exemplified above, you will see that only those with type number
that commented will return true
.
We can also modify "number"
by another type to create a function that checks whether it is string
for example, or if it is boolean
, it's as simple as that.
In fact, it is a disadvantage, depending on the point of view, in Javascript it is not necessary to declare the type and the variable before using it.