Understanding Incrementing

For example this:

var a = 123;
var b = a++;

now a contains 124 and b contains 123

I understand that b is taking the value of a and then a is being incremented. However, I don't understand why this is so. The principal reason for why the creators of JavaScript would want this. What is the advantage to this other than confusing newbies?


That's why it's called the "post-incrementing operator". Essentially, everything is an expression which results in a value. a + 1 is an expression which results in the value 124. If you assign this to b with b = a + 1, b has the value of 124. If you do not assign the result to anything, a + 1 will still result in the value 124, it will just be thrown away immediately since you're not "catching" it anywhere.

BTW, even b = a + 1 is an expression which returns 124. The resulting value of an assignment expression is the assigned value. That's why c = b = a + 1 works as you'd expect.

Anyway, the special thing about an expression with ++ and -- is that in addition to returning a value, the ++ operator modifies the variable directly. So what happens when you do b = a++ is, the expression a++ returns the value 123 and increments a. The post incrementor first returns the value, then increments, while the pre incrementor ++a first increments, then returns the value. If you just wrote a++ by itself without assignment, you won't notice the difference. That's how a++ is usually used, as short-hand for a = a + 1.

This is pretty standard.


Note that you can also write

b = ++a;

Which has the effect you are probably expecting.

It's important to realise that there are two things going on here: the assignment and the increment and the language should define in which order they will happen. As we have available both ++a and a++ it makes sense that they should have different meanings.

For those of us from a C background, this is quite natural. If PHP behaves differently, we might be wondering why PHP chose to deviate from what we are accustomed to.


++ can be used as post-increment operator like in your example, or it could be used as a pre-increment operator if used before variable.

var b = ++a;

Then first the variable a will be incremented, then the incremented value is assigned to b.


This is the standard way of doing it. The postincrement operator assigns the value and then increments.

The preincrement (++a) operator increments and then assigns.

I am not familiar with php and cannot say how it does it or why.