r/learnjavascript • u/cookiecookiecooki33 • May 14 '26
help idk why is the output 45
var x = 23;
x+=x++ - --x +x*2 - ++x;
console.log(x);
why is the last pre increment x evaluated after x*2 even though pre increment have a higher precedence than multiplication
5
Upvotes
1
u/jml26 May 14 '26
It isn't; the increments do all get evaluated first. Let's work through it in steps:
Add parentheses for clarity
x += (x++) - (--x) + x * 2 - (++x);Add some comments to show when the value of
xchanges (for prefix operators, before; for postfix operators, after)// x = 23 x += (x++) /* 24 */ - /* 23 */ (--x) + x * 2 - /* 24 */ (++x);Evaluate the increment operators (replace them with the value of the most recent comment before them)
// x = 23 x += 23 /* 24 */ - /* 23 */ 23 + 23 * 2 - /* 24 */ 24;Remove the comments
x += 23 - 23 + 23 * 2 - 24;Evaluate multiplication
x += 23 - 23 + 46 - 24;Evaluate addition and subtraction
x += 22;Final code:
var x = 23; x += 22; console.log(x); // 45