As far as I've been led to understand, x++
is essentially a terser way of saying x = x + 1
. So far, so clear. In front-end Javascript, I've occasionally seen ++x
— I seem to remember from a jsPerf test I can no longer find (how does one Google ++
effectively?) that this somehow had a small performance benefit in a particular version of IE, and let it go at that.
However I've recently encountered something that speaks of a weird quirk in execution order (JS code):
var x = 1;
console.log(x++); // 1 (?!)
console.log(x); // 2
…whereas
var x = 1;
console.log(++x); // 2 (what I would've expected)
console.log(x); // 2
I can't get my head around this. How can we return the unmodified variable when the operation and assignment are within the parenthesis, and thus by all rights should be executed before console.log
is even invoked, let alone executed and returned?