Reputation: 2071
If I do:
var a = 1;
console.log(a) // 1
console.log(++a) // 2
console.log(a++) // 2
console.log(a) // 3
So to try make sense of this I would say:
var a
.a
now is 1. So it prints 1.console.log
I sum to a 1. So it should print 2. The sum happens BEFORE printing the value.How Javascript works so that this can happen?
Thank you!
Upvotes: 0
Views: 55
Reputation: 10193
The difference between a++
and ++a
is the value of the expression.
a++
is the value of a
before the increment.++a
is the value of a
after the increment.So you can get the result as the question.
Upvotes: 2
Reputation: 8492
This is the difference between a pre-increment and post-increment.
++a
will add 1 before the final value is evaluated.
a++
will evaluate a
and then add ` afterwards.
Upvotes: 3