0

var x=1; for(;x<6;x+=2){ x=x*x; } alert(x); //output= 11 //do u have any explanation?

19th Jun 2017, 9:41 PM
islam moheb
islam moheb - avatar
2 Answers
+ 3
var x = 1; for(; x < 6; x +=2) { x=x*x; } alert(x); First x is declared outside the for loop so that the alert call will be able to access it; When it hits the loop the setup part of the loop "for(;" is empty so it is skipped and the conditional part "x < 6;" is checked. Here x is 1 so 1 < 6 is true and the body {x=x*x;} is executed. x = 1*1; x is still equal to 1 at the end of the loop body. Then the incrementation part "x += 2" is ran 1+2 = 3, x equals 3. Now the conditional is checked again 3 < 6 is true so the body is ran again. 3 * 3 = 9. Then the incrementation part of the loop is ran again 9 + 2 = 11. Then the conditional is checked 11 < 6 is false so the loop exits and the alert is ran with the output of 11.
19th Jun 2017, 10:52 PM
ChaoticDawg
ChaoticDawg - avatar
0
x=1: x=1*1; x=1: x+=2; x=3: x=3*3; x=9: x+=2 x=11: x<6 == false
19th Jun 2017, 10:39 PM
alex
alex - avatar