This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Less_Than_Three
about 11 years

Why won't my while loop work?

var i = 1; for(i = 1; i <= 5; i++){ console.log(i);}

while(i <= 3){ console.log(“A while loop.”); i++;}

do{console.log(“A do/while loop.”);} while(i === 3);

When I run my code, everything works except for the while loop. The string, “A while loop” is not logged three times as is my intention, but the for and do/while loops work fine and I am allowed to proceed to the next section. I still want to know what I did wrong though.

Answer 512497b3d85f5c62a200202f

1 vote

Permalink

Remember that variable i is global. The while loop is not run because the condition is not met. After the running the for loop the value of variable i is 5, which is greater than three. To fix this you should reassign the value before running the while loop (simply add var i=1; between the for loop and the while loop).

points
about 11 years

2 comments

Less_Than_Three about 11 years

Oh man, I forgot that the for loop then changes the value of i for the rest of the loops I write. I just added var i = 1 and it worked. Thanks!

Constantine Kozhevnikov about 11 years

By the way, i=1 works as well, since there is no need to declare the value, we need only to assign a value to it.