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 + 1is an expression which results in the value 124. If you assign this tobwithb = a + 1,bhas the value of 124. If you do not assign the result to anything,a + 1will still result in the value 124, it will just be thrown away immediately since you’re not “catching” it anywhere.BTW, even
b = a + 1is an expression which returns 124. The resulting value of an assignment expression is the assigned value. That’s whyc = b = a + 1works 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 dob = a++is, the expressiona++returns the value 123 and incrementsa. The post incrementor first returns the value, then increments, while the pre incrementor++afirst increments, then returns the value. If you just wrotea++by itself without assignment, you won’t notice the difference. That’s howa++is usually used, as short-hand fora = a + 1.This is pretty standard.