8. When to while and when to for > i'm stuck, it loads forever and crush


#1

ok i'm stuck with this one... trying to avoid the infinite loops by adding 'firstLoop = false;' but it crushes... what is wrong in it, is this the matter of for loop..? thanks...

var firstLoop = true;
var countLoop = 3;

var loop = function() {
    for (var i = 0; i < countLoop + i; i++) {
        console.log("countloop counts " + countLoop);
    }
    while(firstLoop) {
        console.log("firstloop works");
        firstLoop = false;
    }
}

loop();


#2

this:

i < countLoop + i

looks like a bad idea to be honest. lets fill in the numbers for a couple of runs of the loop:

0 < 3 + 0
1 < 3 + 1
2 < 3 + 2
3 < 3 + 3
4 < 3 + 4

and so on, a infinity loop. i will keep increasing, since you add i to countLoop, the condition will never be met, don't add i to countloop


#3

This is indeed a problem with your for loop - you'll notice that if you comment it out, your code runs fine.

The reason you're getting an infinite loop in your for loop is the following condition:

i < countLoop + i

You're basically saying 'run the loop as long as long as i is less than countLoop + i.

i = 0: 0 < (3 + 0)
i = 1: 1 < (3 + 1)
i = 2: 2 < (3 + 2)
...
i = 100: 100 < (3 + 100)

You get the picture. The + i has created a situation where the condition will ALWAYS be true, and thus run the loop until your browser screams in agony.

EDIT: Nevermind, @stetim94 beat me to it!


#4

now he has two explanations he can read, nothing wrong with that :slight_smile: Also good to have multiply explanations, see which one you best understand


#5

Wow Yes you both are GENIUS! my browser screams at me without any noise and i have no idea why it doesn't want to move on O_O

ok... everything makes sense now... and interesting explanations. @stetim94 and @nedwards thank you very much!

i will not be creative in programming languages... gotta follow the rules,
no using i < variableName + i, so it has to be a number after the operator expression, for the 'for' loop function - for the best practice??

i < 3;

i try now.


#6

i have now:

i < 3;
console.log("countloop counts");

and i have now:

i < 3;
console.log(i);

not exactly what i wish for... (in terms of 'plays with the creative juice'), but it worked.

thanks a lot.


#7

not exactly what i wish for

You could always use console.log("countloop counts " + i).

If you want it to count from 1, use (i + 1) instead :slight_smile:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.