+ 2

Help please! I just started learning js. Why is the output of this code 10

var count = 0; for(i=0;i<3;i++){ for(j=3;j>0;j--){ count++; } } alert(++count) //help me to understand thanks!!

18th Jan 2018, 7:42 PM
HRMtech
HRMtech - avatar
3 Answers
+ 6
Each loop executes 3 times, as one is into another, you get 3*3=9 times. Then you increase count before output and get 10.
18th Jan 2018, 7:52 PM
Petr Leliaev
Petr Leliaev - avatar
+ 5
for i=0(condition true) it will enter into next for loop for j=3(condition true) count increments to 1 again j=2(condition true) count increments to 2 again j=1(condition true) count increments to 3 now j=0 (condition false) so j loop terminates again go to i loop for i=1 j=3,j=2,j=1 increments count to 6 i=2 j=3,j=2,j=1 Increments count to 9 i=3(condition false) i loop terminates now our count=9 in the alert section u are pre incrementing so first increments value and then print increments 9 to10 this is how it works hope it helps u
19th Jan 2018, 12:03 AM
gnaneswari kolathuru
gnaneswari kolathuru - avatar
+ 5
First when ■ i=0 ■ j=3 -> j=2 -> j=1 count=3 Second when ■ i=1 ■ j=3 -> j=2 -> j=1 count=6 Third when ■ i=2 ■ j=3 -> j=2 -> j=1 count=9 fourth when ■ i=3 ■ i>3 condition false //count=9 alert(++count) //count=10 alert(10) will alerts 10
19th Jan 2018, 8:41 AM
I'm_Groot
I'm_Groot - avatar