JS newbie here looking for some advice. I've been working through the Head First JavaScript Programming book and it showed me how to log the '99 Bottles of Beer on the Wall' song to the console. Here is the original code:
var word = "bottles";
var count = 99;
while (count > 0) {
console.log(count + " " + word + " of beer on the wall");
console.log(count + " " + word + " of beer,");
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 0) {
console.log(count + " " + word + " of beer on the wall.");
} else {
console.log("No more " + word + " of beer on the wall.");
}
}
Without giving an answer, it suggests that the code is okay but not 100% right, and asks if you can find the flaw and fix it. After looking in the console, I discovered that the while loop doesn't take into consideration that the word "bottles" needs to change to "bottle" once you get down to one bottle of beer in the song. I've added some if statements to the loop to make the var word change to "bottle" when needed. The code appears to work correctly now:
var word = "bottles";
var count = 99;
while (count > 0) {
if (count == 1){
var word = "bottle"
}
console.log(count + " " + word + " of beer on the wall");
console.log(count + " " + word + " of beer,");
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 0) {
if (count == 1){
var word = "bottle"
}
console.log(count + " " + word + " of beer on the wall.");
} else {
if (count < 1){
var word = "bottles"
}
console.log("No more " + word + " of beer on the wall.");
}
}
My question is this - is there a better, or more succinct way to do this than my attempt? I have a feeling my attempt is a bit messy. I know that you can use a For loop for this, but the example used a While loop, so I'd like to stick with that, if possible.
Many thanks!