Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing concatenation

Tags:

javascript

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 page without installing anything. See for example.

The showstopper I've recently discovered is that because JavaScript is loosely typed by design, it keeps concatenating strings when I want it to add numbers. And it's unpredictable. One routine worked fine for several days then when I fed different data into it the problem hit and I ended up with an impossibly big number.

Sometimes I've had luck preventing this by putting ( ) around one term, sometimes I've had to resort to parseInt() or parseFloat() on one term. It reminds me a little of trying to force a float result in C by putting a .00 on one (constant) term. I just had it happen when trying to += something from an array that I was already loading by doing parseFloat() on everything.

Does this only happen in addition? If I use parseInt() or parseFloat() on at least one of the terms each time I add, will that prevent it? I'm using Firefox 6 under Linux to write with, but portability across browsers is also a concern.

like image 353
ab1jx Avatar asked Nov 29 '22 03:11

ab1jx


1 Answers

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;
like image 200
Felix Kling Avatar answered Dec 12 '22 07:12

Felix Kling