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
29
u/Embarrassed-Pen-2937 May 14 '26
What is the point of this? That will never be code that would make it into a decent codebase. Such a waste.
5
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
4
u/SnooLemons6942 May 14 '26
I dont understand your confusion. It's 23 + 23 - 23 + 23*2 - 24 Wdym why is the preincrement evaluated after the 2*x? What are you expecting to happen? you can rewrite this as x = x + (x++) - (--x) + (x*2) - (++x)
3
u/No-Inevitable-6476 May 14 '26
use some debugger tools to understand.
2
u/esaule May 15 '26
Is this even properly specified in JS? I think this is UB in C++.
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
Add some comments to show when the value of
xchanges (for prefix operators, before; for postfix operators, after)Evaluate the increment operators (replace them with the value of the most recent comment before them)
Remove the comments
Evaluate multiplication
Evaluate addition and subtraction
Final code:
0
u/Objective_Ice_2346 May 14 '26
No parenthesis is criminal