Simple calculation between string and integer

3

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.

    
asked by anonymous 26.03.2014 / 16:53

2 answers

6

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.

    
26.03.2014 / 16:57
2

You can always check whether the variable is an integer before dividing. I leave here a Jsfiddle with the example:

Jsfiddle

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)
    
26.03.2014 / 17:02