Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ++ vs +=1

Tags:

javascript

var a = "ab";
var b = "ab";
a+=1; // "ab1"
b++; // "NaN"

(Tested on chrome's V8)

Can someone explain why the results are different based on the internal atomic actions of the ++ arithmetic operator and the += assignment operator with argument 1

like image 358
Raynos Avatar asked Dec 09 '10 11:12

Raynos


People also ask

What is the difference between 1 and 1 in JavaScript?

There is no difference between the numbers 01 and 1 . They are absolutely identical.

Is ++ the same as += JavaScript?

++ increases the integer by one and += increases the integer by the number of your choice.

What does 1 mean in JavaScript?

No, -1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent.

Is i ++ the same as i += 1?

These two are exactly the same. It's just two different ways of writing the same thing. i++ is just a shortcut for i += 1 , which itself is a shortcut for i = i + 1 . These all do the same thing, and it's just a question of how explicit you want to be.


2 Answers

++ converts to number, and then increments, += with a String concatenates.

From the spec:

11.3.1 Postfix Increment Operator

  ...
  3. Let oldValue be ToNumber(GetValue(lhs)).
  4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).

For the a+=1 case, if you add a number to a string or the other way around the number gets converted to a string:

11.6.1 The Addition operator ( + )

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

  8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

like image 77
Ivo Wetzel Avatar answered Sep 20 '22 14:09

Ivo Wetzel


  • ++ tries to increment a Number (if it's not a number, this will fail - resulting in NaN)
  • += is concatenation, in this case the JavaScript engine figures out that one side is a string, so they're both concatenated as strings.

They're different because they're different operations, ++ is specifically an arithmetic operator, where as += is a more general assignment operator that behaves differently based on the data type - specifically, string has its own implementation.

like image 37
Nick Craver Avatar answered Sep 19 '22 14:09

Nick Craver