I understand all of the following code from an example on a book I’m reading. Except the commented line. I’m thinking that without it the loop never ends? I don’t understand the logic behind it though.
var drink = "Energy drink";
var lyrics = "";
var cans = "99";
while (cans > 0) {
lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>";
lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>";
lyrics = lyrics + "Take one down, pass it around, <br>";
if (cans > 1) {
lyrics = lyrics + (cans-1) + " cans of" + drink + " on the wall <br>";
}
else {
lyrics = lyrics + "No more cans of" + drink + " on the wall<br>";
}
cans = cans - 1; // <-- This line I don't understand
}
document.write(lyrics);
This is a loop that starts at 99 (
var cans = "99") then counts backwards to 0. The highlighted line is the line that says “subtract one”. If it weren’t for that line, it would keep looping and adding99 cans of Energy drink on the wallforever.BTW,
document.writeis just bad, andvar cans = "99"should bevar cans = 99. Of course, this probably isn’t your code, just sayin’. My advice: keep reading.