Messy code for While Loops


#1

Have a very messy for and while loops- perhap's I've been staring at it too long? But would really appreciate any help- I know it's really bad so please be gentle. :smile:

var loops=0
while (loops) {
for (i>5; i<10 i++); {
console.log(i);
}

loops (false);

#2

well I can't really see the reason for having a for loop inside of a while loop. That's a nested iterator and it's useful, but only in some circumstances.

The difference between for loops and while loops is simple.

for loops are used when you know exactly how many times the loop is going to run.

while loops are used for times when you don't know how many times the loop needs to iterate.

Let's say you are trying to get the user to put a specific input into the system, but they keep putting in different things, so you'll want to use a while loop telling them to input a certain thing until they do it. You don't know how long it will take them to figure out what they need to input so you'd use a while loop.

However, if you were trying to count to 10, you could do this with a while loop, but you're right, it's messy. It's easiest in that situation to instead use a for loop because you know exactly how many times you want the loop to run.

I hope that explain it for you. If that wasn't good enough let me know and I'll try again.


#3

The above is a call expression to the function loops(), which does not exist. loops is a number value, not a function.

There are a number of errors in the above.

for (iterator_start_value; execution_conditional; step_expression) {

There is no semi-colon allowed between the parameters and the code block.

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

Now the loops variable and the execution conditional in while()...

If loops equals 0 then this loop will never run:

while (loops) { ... }

0 is falsy so will fail the conditional. The number needs to be non-zero to evaluate to a Boolean true.

The simplest approach to this exercise is to keep it simple. If all that is asked for is a while loop, then stick to that statement and don't complicate it by nesting other loops.

var loops = 5;
while (loops) {
    console.log("I'm looping");
}