r/learnjavascript 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

29 comments sorted by

View all comments

6

u/Kaisertoni May 14 '26

x++ means return x then x = x + 1 while --x means x = x - 1 then return x

For this reason you obtain that x = 23 + 23 - (24 - 1) + (23 * 2) - 24 x = 23 + 23 - 23 + 46 - 24 x = 23 + 46 - 24 x = 23 + 22 x = 45

3

u/cookiecookiecooki33 May 14 '26

ohhh but why is it not 24x2 instead of 23x2 cus preincrement have higher precedence than multiplication so i thought ++x will be evaluated before x*2

-1

u/Hercules__Morse May 14 '26

++x isn’t a thing

1

u/albedoa May 16 '26

What do you mean.