8/11 When to 'while' and when to 'for'


#1



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


I tried to implement a while loop and a for loop in the function twoloops but I get the error 'SyntaxError: Unexpected token for'.


var count = 0

var twoloops = function() {
    while (count < 3) {
        console.log("This is a while loop");
        count++;
    }
    
    var (for i = count, i < 3, i++) {
        console.log("This is a for loop");
    }
};

twoloops();


#2
var count = 0 //add semicolon

var twoloops = function() {
    while (count < 3) {
        console.log("This is a while loop");
        count++;
    }
    
    var (for i = count, i < 3, i++) { //just do a for loop; should be "for (i = count, i < 3, i++) {"
        console.log("This is a for loop");
    }
};

twoloops();

That should help :slight_smile: My comments have // before them.


#3

Thanks @chipsolver68217, I tried this but got the error 'i is not defined', is the function wrong because of my for loop?


var count = 0

var twoloops = function() {
    while (count < 3) {
        console.log("This is a while loop");
        count++;
    }
    
    for (i = count, i < 3, i++) {
        console.log("This is a for loop");
    }
};

twoloops();


#4

Any time! I see the problem: the for loop currently reads
for (i = count, i < 3, i++)
But you need to declare the variable i, since it doesn't already exist. Sorry I didn't point it out before!
for (var i = count, i < 3, i++)


#5

@mabviro omission of the var keyword is not the problem (if you don't use a strict mode of course). When we do something like var i = 0 we create a variable i in the current scope. i = 0 will try to find variable i in the scope chain and make the assignation, if variable i is not present in the upper scopes it will be added as the property to the global object.

Simply speaking - always use var.


What is the real problem? The for loop.

As you probably know we define for loop by providing three expressions:

  1. expression that will be executed at the beginning;
  2. condition that will be checked before starting next iteration;
  3. expression that will be executed after every iteration.

You have used commas to separate these parts. Because of that, the interpreter is treating i = count, i < 3, i++ as a single complex expression and is still waiting for two next parts. You can find more about the comma operator here -> MDN: Comma operator.

To fix this problem you just have to change commas in the for loop to semicolons.


#6

Another dumb mistake by me, I'm off today...


#7

It wasn't a dumb mistake. It was a good call. var is a really important keyword and it's good that you pointed this out.

I am not an authority, but just a small hint from me -> always remember to try to execute code posted by the user. It takes time, but there is a high chance that you will not miss anything :slight_smile: