How does a postfix ++ operator works :
var a = 100;
var b = a++ + a;
//Result 201
Here if 'a' is incremented then should not the value be 202. And if it is true then should not be the next equation value 301 ?
var a = 100;
var b = a++ + a + a;
//Result 302
In
var a = 100;
var b = a++ + a;
what happens is:
a
is set to 100
a++
is evaluated. The value of that subexpression is 100
. Also, a
is set to 101
.a
(101
) is added to the value of the left-hand subexpression (100
).b
is set to the result, 201
.The postfix ++
operator returns the value of the variable as it was before the increment. The prefix ++
operator (as in ++a
) performs the increment and gives the value after that.
The behavior in JavaScript is the same as in many other languages with expression syntax and semantics derived from C.