2.1 Practice Makes Perfect - placing of count++


#1

I'm a little confused with the placing of the count++ parameter. I thought it should go into the While parameters, but apparently it needs to be in the function.

Is this because of the syntax of While loops compared to For statements?

This results in an error

//Remember to set your condition outside the loop!
var count = 0

var loop = function(){
while(count < 3; count++){
//Your code goes here!
console.log("I'm looping!");
}
};

loop();

But this doesn't

//Remember to set your condition outside the loop!
var count = 0

var loop = function(){
while(count < 3){
//Your code goes here!
console.log("I'm looping!");
count++
}
};

loop();

I was wondering whether someone could expand on this a little. I am guessing it's because they have different syntaxes

FOR (initialise, test, inc-/dec-rement)

WHILE(test){
do this
inc-/dec-rement
}

Is that correct?


#2

Hi @algrfalls10

Your second while loop is correct :

var count = 0;

var loop = function(){
    while(count < 3){
        //Your code goes here!
        console.log("I'm looping!");
        count++;
    }
};

loop();

Only condition inside () after while

while( condition, with comparator, or not){
    //code execute condition while is true
}

#3

Thanks, I understand the second on is correct, I was wondering why, but it is actually explained in the Hints section of a following exercise - it's syntax.

This is what the hint says (for anyone from the future reading this):

Remember your syntax! While loops look like this:

while(condition) {
// Do while condition is true
}
For loops look like this:

for(start; end; increment) {
// Do something!
}
For example, you might have a for loop that looks like this:

for (var i = 1; i < 11; i++) {
// Print the numbers 1 - 10
console.log(i);
}

:grin:


#4

There is a way we can do this, sort of...

var count = 0;     // declare and initialize control variable

while (3 > count++){
    console.log(count);
}
/*
1
2
3
*/