Skip to content Skip to sidebar Skip to footer

Preventing Concatenation

I've been writing JavaScript on and off for 13 years, but I sort of rediscovered it in the past few months as a way of writing programs that can be used by anyone visiting a web pa

Solution 1:

The specification says about the addition operator:

If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

Which means that if at least one operator is a string, string concatenation will take place.

If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it?

No, all operands have to be numbers.

You can easily convert any numerical string into a number using the unary plus operator (it won't change the value if you are already dealing with a number):

var c = +a + +b;

Solution 2:

I normally do this:

var x = 2;
var t = "12";
var q = t+x; // q == "122"
var w = t*1+x; // *1 forces conversion to number w == 14

If t isn't a number then you'll get NaN.

If you multiply by 1 variables you don't know what type they are. They will be converted to a number. I find this method better than doing int and float casts, because *1 works with every kind of numbers.

The problem you are having is that the functions which fetch values from the DOM normally return strings. And even if it is a number it will be represented as a string when you fetch it.


Solution 3:

You can use + operator to convert a string to number.

var x = '111'
+x === 111

Solution 4:

Rest assured it is very predictable, you just need to be familiar with the operators and the data types of your input.

In short, evaluation is left-to-right, and concatenation will occur whenever in the presence of a string, no matter what side of the operation.

So for example:

9 + 9 // 18
9 + '9' // '99'
'9' + 9 // '99'
+ '9' + 9 // 18 - unary plus
- '9' + 9 // 0 - unary minus

Some ternary expressions:

9 + '9' + 9 // '999'
9 + 9 + '9' // '189'

Post a Comment for "Preventing Concatenation"