When to 'while' and when to 'for' -help!


#1

https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/1?curriculum_id=506324b3a7dffd00020bf661#

ReferenceError: i is not defined


var myLoop = true;
while(myLoop) {
    console.log("This should work");
    myLoop = false;
    }

for(i < 0; myLoop.length; i++) {
    console.log("This is me!");
    }

The instruction given is as follows: "Write two loops in the editor: one while, one for. No restrictions on this one; just make sure your loops are syntactically correct, and be careful to avoid infinite loops!"


#2

while is indefinite, whereas for is set to iterate over a range.

If you cannot count ahead of time the number of iterations, then while is what to use. Set an execution condition that must be met in order for the loop to run or continue. Code inside the loop should change that condition or there should be a conditional break. while is an infinite loop when not given a break condition.


#3

Thanks @mtf Can you please tell me the correct syntax?


#4

There are a few ways to use for but the most common form is,

for (var i = 0; i < someValue; i++) {

}

someValue may be a fixed number literal, or it could be the length of a string or array being iterated.

i < array.length

i < string.length

Always less than to account for zero-indexing.

When writing a while loop, start with a skeleton:

while (condition) {
    break;
}
console.log("Bye");

I output Bye when building a while loop to indicate that the loop has finished, then remove the line when everything is ship-shape and Bristol fashion.

Eg.

while (true) {
    if (Math.random() < 0.1) break;
    console.log("Still looping");
}
console.log("Bye");

There are lots of ways to utilize a while loop. A do..while is very much the same with one exception. It executes at least once. A while loop can only execute if the condition evaluates to true, to start with. The do loop checks the condition at the end.


#5

Thanks a lot @mtf I get it now. It worked. I really appreciate.


#6

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