Help against Infinity Loops/While Loops


In for loops how do you avoid "infinity loops"? I seem to run into those a lot and I cannot figure out why. Please help with this. Thanks


Share your code so we can help identify where you are going wrong


Could you show a example of a infinity loop and a good loop?

var count = i;
for (i = 1; i >= 1; i++) {
    console.log("This will run forever");

The above code is an infinite loop. The following code is not

var count = i;
for (i = 1; i < 10; i++) {
    console.log("this statement should print 9 times");


so the end code cannot have an "=". Thanks @vinceknight


No that isn't what I mean at all. The end code could look like:

var count = i;
for (i = 1; i <= 10; i++) {
    console.log("This statement should print 10 times");


so the "end" part cannot have the same number as the "start?"


Easiest way to explain this:

for (i = 1; i >= 1; i++) {

in the above line it says: "i = 1" meaning i is 1. This is the first thing the program sees. From here it looks at the middle piece "i >= 1" which in this case says that when i is greater than or equal to 1 run the code. After it finishes running the code it looks at the last bit which is "i++' Which is short hand for i + 1. Then it goes back to the beginning where i is now equal to 2 and therefore is greater than or equal to 1 and so the code keeps running over and over again because there is no end


I see now! Thank you @vinceknight. I will probably need you again sometime because I am kinda new to this JS.


no problem I'll keep this window open. Just remember that the middle section of your for loop (meaning the bit that says i >= 1 in the above example) is what tells your loop to stop. and try reading your code like a "story" like I did in the explanation it may help you to keep things under control a bit better. Good luck and keep coding


Now I am on While loops and I have run into another problem. How would you log something into the console three times?


Nevermind on that problem. I have run into another wall.

var count = 0

var loop = function(){
console.log("I'm looping");


This code crashes my browser but I don't know why. This is from Introduction to 'While' Loops in JS lesson 5. THX


Sorry for no response I am also at that section but haven't had a chance to work on it. Just got my main PC back up and running. Will try to get onto that today to see if I can help. Don't know if you are still stuck in that section or not. Apologies


The reason it crashes is because it is going into an infinite loop. It is going into an infinite loop because you aren't changing the variable count.

After console.log try adding a line like:

count = count + 1;

this will add 1 to count every time the loop runs thus allowing:

while(count < 3){

to eventually equal false.