tags:

views:

69

answers:

3
var num = "1";
num = num+1; //Gives "11"

but

 var num = "1";
 num++; //Gives 2.

Why?

+5  A: 

Because the + operator is also used for string concatenation.

var num = "1";
// The 1 is converted to a string then concatenated with "1" to make "11".
num = num+1;

Javascript is a weakly typed language, so it's more lenient about type conversions.

The ++ operator used in your case is the postfix increment operator which only operates on numbers, so it acts as you expect:

var num = "1";
// num is converted to a number then incremented.
num++;

To give a hint that addition should take place, subtract by zero:

var num = "1";
// Subtraction operates only on numbers, so it forces num to be converted to an
// actual number so we can properly add 1 to it
num = (num - 0) + 1;

Or use the unary + operator:

var num = "1";
// The unary + operator also forces num to be converted to an actual number
num = (+num) + 1;
In silico
+1  A: 

Because ++ is an numeric operation, so num is cast from string, then the operation takes place.

The + however can be both for numeric operands (add), as well as string operands (concatenation). So 1 is cast to string, then concatenated with 1, which gives 11.

Alexander
A: 
var num = "1";
num = num+1; //Gives "11"

First one is, + operator is string concatenation. So you get the concatenation result.

 var num = "1";
 num++; //Gives 2.

Second one is, ++ operator is post increment operator. So you get the added result.

If you wish to change the + operator for addition. Use like this

 var num = "1";
 num = parseInt(num)+1; //Gives "2"

The parseInt() function parses a string and returns an integer. So it return the integer value.

Karthik