How to prevent this from happening?
asd = "10"
novo=asd/2;
console.log(novo) // e ele me retorna 5
Being asd
is a string and can not be debt and treated as integer.
How to prevent this from happening?
asd = "10"
novo=asd/2;
console.log(novo) // e ele me retorna 5
Being asd
is a string and can not be debt and treated as integer.
It's a language feature, JavaScript is weakly typed .
You can check the type of your variables is actually a number before proceeding, if you want:
if (typeof(asd) == "number")
novo = asd / 2;
else
throw "Tipo inválido";
More details about this check: How do I tell if a variable is a Number type in JavaScript?
But this goes against the "spirit" of js. If you create a function that works with a numeric argument, a user can of course expect that if he passes a string, it will work.
You can always check whether the variable is an integer before dividing. I leave here a Jsfiddle with the example:
What I'm doing is:
I have a regular expression that defines integers
var verifyInt = /\d+/g; // Expressão regular
2- And with match
check whether it is integer or not
if (asd.match(verifyInt) != null)