This forum is now read-only. Please use our new forums! Go to forums
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
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).
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
2 comments
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!
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.