borjagvo
borjagvo

Reputation: 2071

Why Javascript acts like this?

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:

  1. Assign 1 to var a.
  2. a now is 1. So it prints 1.
  3. Now, INSIDE function console.log I sum to a 1. So it should print 2. The sum happens BEFORE printing the value.
  4. Why the value 1 is added to a AFTER printing the actual value of a? This is what I don't get.

How Javascript works so that this can happen?

Thank you!

Upvotes: 0

Views: 55

Answers (2)

Derek Wang
Derek Wang

Reputation: 10193

The difference between a++ and ++a is the value of the expression.

  • The value a++ is the value of a before the increment.
  • The value of ++a is the value of a after the increment.

So you can get the result as the question.

Upvotes: 2

abney317
abney317

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.

See Increment (++) Reference

Upvotes: 3

Related Questions