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


#1

Below is my code. The lesson said it was correct and enables me to move on, but my code did not print anything. Is there something I am not understanding?

Thanks in advance!

var Christmas = function(){
var Christmas = 0;
while(Christmas < 3) {
console.log ("We Wish You a Merry Christmas,");
}
for(var Christmas = 4; Christmas > 3; Christmas++) {
console.log ("And a Happy New Year!");
}
};


#2

Multiple problems...

  1. You wrapped both loops in a function called Christmas but then you don't execute it, so nothing runs.

  2. If you do call it using Christmas(); then you will notice you will crash your browser, your while loop is never ending

  3. Your for loop logic is never-ending too, because it starts at 4 and it will always be greater then 3.

  4. Finally your using the variable Christmas for everything.. this is not good. You're shadowing the Christmas variable. This is not smart to do when coding if you fix everything it will run but it's not good to use the same variable recursively, normally in code variables are holders needed at some later point and if you keep over-wiring them you lose data.


#3

Wow, I didn't realize I had so many issues! Curious, since it told me I could move on... I fixed the top part, but my "for" loop still doesn't print. Here is my revised code:

var Song = function(){
var Christmas = 0;
while(Christmas < 3) {
console.log ("We Wish You a Merry Christmas,");
Christmas++;
}
for(var Christmas = 4; Christmas > 4; Christmas++) {
console.log ("And a Happy New Year!");
}
};

Song();


#4

Well all loops run when their conditions are true. So when you have a look at the condition of your for loop:

Christmas > 4
and the value of Christmas:
var Christmas = 4

you can see that 4 is not greater than 4 so the loop doesn't start. Also it is quite odd to use a loop if you want to do something once but I guess that is part of the instructions, isn't it?