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

15th May 2022, 2:09 PM
Harsha S
Harsha S - avatar
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.
15th May 2022, 2:26 PM
Paul
Paul - avatar
+ 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..
15th May 2022, 2:35 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 thank you but I am not able to get it completely
15th May 2022, 2:40 PM
Harsha S
Harsha S - avatar
+ 1
Paul that's interesting
15th May 2022, 2:41 PM
Harsha S
Harsha S - avatar
+ 1
0 += 1-1 1 += 2-2 2 +=3-3 Basicaly you are doing x += 0
15th May 2022, 2:44 PM
Raul Ramirez
Raul Ramirez - avatar
+ 1
Raul Ramirez how is it 1-1, 2-2, 3-3 and so on...?
15th May 2022, 2:46 PM
Harsha S
Harsha S - avatar
+ 1
Cpu calculates right to left
15th May 2022, 2:48 PM
Raul Ramirez
Raul Ramirez - avatar
+ 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..
15th May 2022, 2:55 PM
Jayakrishna 🇮🇳
+ 1
Thanks Jayakrishna🇮🇳 ! I got it now.
15th May 2022, 2:56 PM
Harsha S
Harsha S - avatar
+ 1
Harsha S no but it does have an order of operations similar to it
15th May 2022, 2:56 PM
Raul Ramirez
Raul Ramirez - avatar
+ 1
You're welcome..
15th May 2022, 3:01 PM
Jayakrishna 🇮🇳
+ 1
I use vscode to debug things, i hope this helps 🙂
17th May 2022, 7:23 AM
Chris
Chris - avatar
0
No error when i ran it
15th May 2022, 2:15 PM
Raul Ramirez
Raul Ramirez - avatar
0
Raul Ramirez yeah, right. i forgot that. but does it not follow BODMAS too?
15th May 2022, 2:49 PM
Harsha S
Harsha S - avatar
0
Dada Praise Oluwatomiwa so, how did you learn to copy paste?
17th May 2022, 8:09 AM
Harsha S
Harsha S - avatar