-2

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?

4
  • 2
    is nothing unexpected, ++a is added before which is 2 from 1, a++ is added after so its still 2, then last is outputting 3 because it was added in prev line Commented Sep 30, 2020 at 20:32
  • 2
    Do you know the difference between pre-increment and post-increment? You may need to look more closely here. These have a different behaviour for a reason. Commented Sep 30, 2020 at 20:33
  • in number 3, when you say "I sum to a", you should instead say "I pre-increment a". Commented Sep 30, 2020 at 20:34
  • Didn't know that a console.log() could execute instead of just printing the variable Commented Sep 30, 2020 at 23:04

2 Answers 2

3

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 1 afterwards.

See Increment (++) Reference

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.