11. Review (for, while and do loops: Syntax errors!)


#1

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

Hi, I've been twisting my brain around the loop review session for a long time. I keep getting Syntax errors.
Can you spot mine?

var a = 1
var fLoop = function () {
    for (var a = 1; a < 11; a ++) {
    console.log(a);
}
};
fLoop(a);

var b = 3
var wLoop = function () {
    while (var b < 4) {
    console.log("This while loop should print once!");
    var b ++;
    }
};
wLoop(b);

var c = 7
var dLoop = function () {
    do {console.log("This do loop should print once!");
    };
    while (var c < 6);
    var c++;
}
};
dLoop(c);

SyntaxError: Unexpected token var

Please help. Thanks!


#2

Why use a var in your while statements after already declaring so. It could be confusing the computer. Try this.

Hope it helps! :smile:


#3

Thanks @bayoishola20. I took out the var's, it helped but I'm still having problems.

It said "unexpected token ++" so I also removed these ones:

...Still doesn't pass :frowning:


#4

Currently looks like this:

var a = 1
var fLoop = function () {
    for (var a = 1; a < 11; a++) {
    console.log(a);
}
};
fLoop(a);

var b = 3
var wLoop = function () {
    while (b < 4) {
    console.log("This while loop should print once!");
    b++;
    }
};
wLoop(b);

var c = 7
var dLoop = function () {
    do {console.log("This do loop should print once!");
    };
    while (c < 6);
    c++;
}
};
dLoop(c);

#5

Well, there are quite a number of more issues and I don't know what you intend to achieve; I can only guess it.

Below is a guide:

var fruit = ["Mango", "Orange", "Berry", "Apple"];
var i = 0;
var text = "";

while (fruit[i]) {
    text += fruit[i] + "<br>";
    i++;
}

Now, when you use the increment, it kind of scans that list or what have you but your code seems to confuse the interpreter. Correct with the guide above.

Also in your do-while loop, pay attention to infinite loops and avoid them. Below will guide you also.

do {
    text += "The number is " + i;
    i++;
}
while (i < 5);

I hope this now helps! :smile:


#6

guess this is the problem. The correct syntax for a do while loop is:

do{
    code 
}
while(condition);

So the semicolon after the } of the do could be a problem and you better keep in mind that the c++ after the loop is well calculated after the loop so don't rely on this one stopping your loop (it currently doesn't, just want to emphasize it).


#7

Thanks for your help!


#8

You're welcome.

Have fun coding! :slight_smile: