# Thread: 1 + 1 will output 11 and not 2...

1. Regular Coders Join Date
Aug 2006
Posts
130
Thanks
0
Thanked 0 Times in 0 Posts

## 1 + 1 will output 11 and not 2...

Hello, got a problem with addition, I have a function that will need a number. Like:
my_function(numb)

and now I want to get the next number (numb + 1) but It will output as 11 instead of 1 + 1 = 2..
I tried to use this:
var next = numb + 1..

and this:
var next = 0;
next = numb + 1;

and this:
var one = 1;
var next numb + one;

but it will give me the same result all the time, the previous (-1) works great but not the +1..  Reply With Quote

2. ## Try numb++, usually that works.  Reply With Quote

3. Regular Coders Join Date
Aug 2006
Posts
130
Thanks
0
Thanked 0 Times in 0 Posts

## thanks it worked.  Reply With Quote

4. ## The + operator in Javascript is overloaded: it performs two quite distinct functions. It performs arithmetical addition on numbers, but concatenation on strings. The latter always takes precedence over the first, so if a string is involved on either side of the operator, concatenation will occur. That is to say:
Code:
```1 + 1 == 2;
1 + "1" == "11";
"1" + 1 == "11";```
If you're not sure whether you're dealing with a number or a string, be safe and convert it. There are several methods of doing this:
Code:
```new Number(n);
parseFloat(n, 10);
parseInt(n, 10);
n - 0;
-n;
+n;
n * 1;```  Reply With Quote

5. ## Isn't the easiest way, then to do
a + 1*b; ?
(Assuming you know that a is a constant, or that a is declared literally as an integer, say 3 + 1*b; )

Or, you could just subtract it's opposite:

a-(-b);

That's probably the easiest, in fact. This would, since it's a mathematical operation without a string-alternative, convert both a and b, I'd assume, so it's a very efficient way to do all of this at once.  Reply With Quote

6. Senior Coders Join Date
May 2007
Location
USA
Posts
373
Thanks
2
Thanked 4 Times in 4 Posts

## Are the (a+b*1) or (a- -b) shorthands executed faster than the parse functions?  Reply With Quote

7. ## My guess would be that any simple math function would be faster than any more complex function.  Reply With Quote

8. ## Yes, +"3" performed an average of 0.0053ms faster than parseInt("3", 10) over 100,000 iterations in SpiderMonkey.  Reply With Quote

9. Junior Coders Join Date
Jul 2007
Posts
7
Thanks
0
Thanked 0 Times in 0 Posts

## I would just do this:

var next=numb-0+1;  Reply With Quote

10. ## Personally, I prefer the form:
Code:
`var next = +numb + 1;`
However, be aware that parse(Int|Float) don't do quite the same things as the simple operator trickery; they will ignore trailing characters, for a start. +"3j" is NaN, but parseInt("3j") is 3.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•