Vad Zelenin Vad Zelenin - 2 months ago 20
Javascript Question

Js magic need explanation

I'm trying to solve this magic in js:

var a = 1;
console.log(a++ + ++a);


It returns 4 and I can understand that it's 1+3 but what is the sequence of this?

Answer

a++ means return the value before incrementing

++a means returns the value after incrementing

So to break down your example:

var a = 1;
console.log(a++ + ++a);
  1. a is set to 1
  2. a++ returns 1, and then a is incremented to 2 (but we don't do anything with it at this point)
  3. ++a increments a and returns 3
  4. Then altogether we have console.log(1 + 3) with the 1 coming from step 1 and the 3 coming from step 3.