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

but

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

Why?

4 Answers 4

5

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
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.

Comments

1

Actually you are storing the string in num variable and it concatenates with num. For storing number you have to remove quotes around 1 while storing it into a num variable.

var num = 1; num = num + 1;

Now the result will be 2 instead of 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.