It is simple to know if a variable is Numero
or not because there is a native Javascript operator that says the type of its variable, which would be the operator typeof
, 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’s an example of a function that checks if the type is number
function isNumber(val){
return typeof val === "number"
}
By testing all the values I exemplified above, you will see that only the ones with type number
that I 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 that simple.
In fact, it is a disadvantage, depending on the point of view, in Javascript it is not necessary to declare the type and variable before using it.
Maybe you’ll find the Typescript interesting.
– hugomg