The type of data in an expression may confuse some script operations if the expected components of the operation are not of the right type. JavaScript tries the most to perform internal conversions to avoid such problems, but it can not read your mind. If your intentions differ from the way JavaScript handles the values, then you will not get the results you expect.
A particularly interesting case is the sum of numbers that can be in the form of text strings. In a simple arithmetic statement, which adds two numbers, you get the expected result:
var soma = 3+3;
console.log(soma);
But if one of these numbers is string, JavaScript has the tendency to convert the other value to a string - transforming the signal action more than arithmetic sum for string association (or concatenation). Therefore, in the statement 3+"3"
the strength of the string in the second value prevails over the entire operation. The first value is automatically converted to string, and the result associates the two strings.
var soma = 3+"3";
console.log(soma);
See what happens when another number is added to the statement: 3 + 3 + "3"
var soma = 3 + 3 + "3";
console.log(soma);
There is a logic behind this result. The expression is evaluated from left to right. The first plus operation works on two numbers, generating the value 6. But when 6 is to be added to "3", JavaScript allows the force of string "3" to prevail. The 6 is converted to string and the two values are concatenated resulting in 63.
Note that in these cases the +
operator before strings did not convert the string to integer!
If a numeric value is stored as a string, your scripts will have difficulty applying this value to a math operation. The JavaScript language provides two built-in functions for converting string representations of numbers into true numbers: parsInt () and parseFloat ().
CONCLUSION
The correct function to use is parseInt()
var soma = 3 + 3 + parseInt("3");
console.log(soma);