0
Can someone debug this for me?
var x = 0; for(; x <= 8; x++){ x += x - x++; console.log(x); } console.log("final value: ", x); //i found this in a javascript challenge
15 Respostas
+ 3
I ran it on my pc, in vs code. It works fine. But I think the third line isn't doing much. When I comment it out, the result is the same.
+ 2
I think, it will be evaluated like
x = x + ( x - x--) ; // the post increment here x-- is pushed into stack for evaluation separately.. then x = x + 1 is updated. But previous calculatuon
x+( x- x--) is evaluated and result is stored in x so overrites x++ value with x +(x-x) which is just equalto x = x + ( x - x) ;
So in loop, x value unchages..
Final value : 9
Hope it helps..
+ 1
Jayakrishna🇮🇳
thank you but I am not able to get it completely
+ 1
Paul that's interesting
+ 1
0 += 1-1
1 += 2-2
2 +=3-3
Basicaly you are doing x += 0
+ 1
Raul Ramirez
how is it 1-1, 2-2, 3-3 and so on...?
+ 1
Cpu calculates right to left
+ 1
Because post increment, the value uses first in expression then increment
So x - x++ is done like x - x, x++
x += x - x++ is done like
x = ( x + ( x - x ) ), x++
x++ update x but it is overritten by value ( x + ( x - x)) which is actually equal to (x - 0) => x
Instead of storing back in x , use any other variable, you can see x++ value .
I thought, your doubt is in
x += x - x-- result.
Where you not understood my reply.. Tell about specific lines..
But hope it clears now..
+ 1
Thanks Jayakrishna🇮🇳 !
I got it now.
+ 1
Harsha S no but it does have an order of operations similar to it
+ 1
You're welcome..
+ 1
I use vscode to debug things, i hope this helps 🙂
0
No error when i ran it
0
Raul Ramirez yeah, right. i forgot that.
but does it not follow BODMAS too?
0
Dada Praise Oluwatomiwa
so, how did you learn to copy paste?