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


<Below this line, add a link to the EXACT exercise that you are stuck at.>


<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>

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!”);

<do not remove the three backticks above>

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!"

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.

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

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) {

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.


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

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.

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

1 Like

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