+ 2

In function a() why is x and y have the exact same output, can anyone explain the logic?

function a(){ for(x=1;x<5;x++){ x+=x; } for(y=1;y<6;y++){ y+=y; } console.log(x); console.log(y); } a();

24th Mar 2017, 9:34 AM
John Watson
John Watson - avatar
2 Answers
+ 4
Starting with x = 1, we get x +=x => x = 1 + 1 = 2; Then x++ resulted into x = x + 1 = 2 + 1 = 3 Now x = 3 which is less than 5, loop continues, we get x +=x => x = 3 + 3 = 6; Again x++ resulted into x = x + 1 = 6 + 1 = 7 Now since the 7<5 failed, loop exits. Same is for variable y
24th Mar 2017, 10:18 AM
à€Šà„‡à€”à„‡à€‚à€Šà„à€° à€źà€čà€Ÿà€œà€š (Devender)
à€Šà„‡à€”à„‡à€‚à€Šà„à€° à€źà€čà€Ÿà€œà€š (Devender) - avatar
+ 2
Thanks Devender Mahajan
24th Mar 2017, 10:59 AM
John Watson
John Watson - avatar