Undefined variable in part of the loop, output - javascript

I am a beginner in JS and I am wondering why the first loop result, outputs an "undefined" variable but the rest have the"bottles" included. It is meant to output a statement, from 99 to 1.
Here is a snippet of the code:
/*
* Programming Quiz: 99 Bottles of Juice (4-2)
*
* Use the following `while` loop to write out the song "99 bottles of juice".
* Log your lyrics to the console.
*
* Note
* - Each line of the lyrics needs to be logged to the same line.
* - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
*/
var num = 99;
let statementSplit = ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
// var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);

The bottles is not encased in double quotes in your let statementSplit... line the very first time that you call it. Instead, it should be
let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));

Try with the edited snippet. The bottles should be added as a string and not as a variable when it is declared in the beginning.
/*
* Programming Quiz: 99 Bottles of Juice (4-2)
*
* Use the following `while` loop to write out the song "99 bottles of juice".
* Log your lyrics to the console.
*
* Note
* - Each line of the lyrics needs to be logged to the same line.
* - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
*/
var num = 99;
let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
// var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);

As stated by other you indeed have an undefined variable in the first statementSplit assignment.
I would move the first statementSplit assignment inside the while loop as well, as to increase maintainability (in case you need to change the lyrics in the future):
var num = 99;
let statementSplit = "";
while (num > 0) {
var bottles = (num > 1 ? "bottles" : "bottle");
statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
num = num - 1;
}
console.log(statementSplit);

Replace "let" with "var" , with var java script allow "hoisting" ...

Related

JavaScript 99Bottles - Infinite Loop

(I already know that this isn't the most elegant solution to the 99 bottles code challenge, but I'd really like to know how not to repeat this mistake in the future.)
When this runs in the console it repeats the (count === 0) condition and repeats nothing but the "0 bottles of beer" console log until it crashes.
I've experimented with using a 'break' statement after the count decrements to 0, but haven't had any success.
let count = 99;
function bottlesOfBeer() {
while (count >= 0) {
if (count > 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
count--;
console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");
};
if (count === 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
} //*this is where I tried the break statement*
}
};
bottlesOfBeer();
You only decrement count when it is above 0, so it never goes below 0; but the loop continues as long as count >= 0.
Here's the corrected code:
function bottlesOfBeer() {
var count = 99;
while (count > 0) {
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
count--;
console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");
}
console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
};
bottlesOfBeer();
Please read and understand - and ask, if you have questions.
In the code, count was set to 99.
The while loop stops when count gets to zero.
When the loop exists, count IS zero, and the appropriate line of the song is logged.
I've removed blank lines...
Other than that - your code is pretty neat: no weird indentations (you wouldn't believe what I see - not that it would effect execution, just easier to read).
Turn while (count >= 0) into while (count > 0) and you are good to go!
The problem is that when it reaches zero you just log the message without decreasing it any more, so it stays zero and (count >= 0) is always true.

My code isn't recognizing a condition

I am trying to solve this following problem (Udacity's Intro to Javascript):
Directions:
Write a loop that prints out the following song. Starting at 99, and ending at 1 bottle.
Example:
99 bottles of juice on the wall! 99 bottles of juice! Take one down, pass it around... 98 bottles of juice on the wall!
98 bottles of juice on the wall! 98 bottles of juice! Take one down, pass it
around... 97 bottles of juice on the wall!
...
2 bottles of juice on the wall! 2 bottles of juice! Take one down, pass it around... 1 bottle of juice on the wall!
1 bottle of juice on the wall! 1 bottle of juice! Take one down, pass it around... 0 bottles of juice on the wall!
and my code doesn't appropriately output the last line (it doesn't include "s" after "bottle"):
My code looks like this:
var num = 99;
while (num >= 1) {
num == 1 ? ((plural = "") && (nextPlural = "s")) :
num == 2 ? ((plural = "s") && (nextPlural = "")) :
((plural = "s") && (nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + "bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
why is this code ignoring my condition for "num == 2?" at the last line of output?
FYI, I was able to solve this using the following code, but it didn't look clean so I wanted to optimize this:
var num = 99;
var plural = "s";
var nextNum = num - 1;
var nextPlural = "s";
while (num >= 1) {
if (num > 1 && nextNum > 1){
plural = "s";
nextPlural = "s";
}
else if (num > 1 && nextNum == 1){
plural = "s";
nextPlural = "";
}
else if (num == 1 && nextNum <= 1){
plural = "";
nextPlural = "s";
}
console.log(num + " bottle" + plural + " of juice on the wall! " + num + " bottle"+ plural + " of juice! " +
"Take one down, pass it around... " + nextNum + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1;
nextNum = num - 1;
}
Alright, so the question, if I understand it right, is why the last line for the first code sample outputs "0 bottle" instead of "0 bottles".
So let's translate what you attempted to achieve with your code into English and figure out what the interpreter does:
Set num to 99.
While num greater or equal to 1, do the following:
2.1 If num equals 1, set plural to "" and nextPlural to "s".
2.2 Else if num equals 2, set plural to "s" and nextPlural to "".
2.3 Else set both plural and nextPlural to "s".
The console output is trivial, so I won't mention it here.
Set num equal to num-1.
You might notice that substituting the ternary operator with an if statement yields the correct result:
var num = 1;
var plural = '';
var nextPlural = '';
while (num >= 1) {
if(num==1) { plural = ''; nextPlural='s'; }
/*num == 1 ? ((plural = "") && (nextPlural = "s")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));*/
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
What does that mean? That there is a syntax error with your use of the ternary operator. What could it possibly be? Let's declare a new variable and try setting and outputting it along with the others.
var num = 1;
var plural = '';
var nextPlural = '';
var test = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? ((plural = "") && (nextPlural = "s") && (test = "test")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
console.log(test);
num = num - 1
}
You will notice that test remains equal to an empty string, just like nextPlural. That's because using && is not the correct way of instantiating variables inside ternary constructions, so this code will work as intended:
var num = 99;
var plural = '';
var nextPlural = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? (plural = "", nextPlural = "s") : (num == 2 ? (plural = "s", nextPlural = "") : (plural = "s", nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
--num;
}
If you are interested, this is how I would probably program the solution:
for(var i=99, w=' on the wall!'; i>0; i--) {
console.log(returnEmpties(i)+w+' '+returnEmpties(i)+'! Take one down, pass it around... '+returnEmpties(i-1)+w);
}
function returnEmpties(n) { return n+' bottle'+(n==1?'':'s')+' of juice'; }
The ternary operator stuff is just a big mess, I've tried to figure it out, but it's really worth trying to fix since it's just not a good idea to use ternary operators like that. You've nested a ternary inside another ternary and basically have an if, else if, else condensed into 3 lines.
You can avoid doing extra logic and realize that you need only add an 's' when the number is not 1.
By extracting this logic into a function that returns the string 's' or the empty string '', you can simply plug this function into your loop and provide it with n and n-1.
function plural(n) {
return n == 1 ? '' : 's'; // note this is the appropriate usage of a ternary operator
}
You can then simply your loop to just
while (num >= 1) {
console.log('...'); // left as an exercise for you to fill in the required function call and string concatenations.
num--; // same thing as num = num - 1;
}

Javascript number guessing game

I can't seem to make this code alert the user when the correct answer is found, nor can I make the pop-ups continue to loop to play again. I coded this as a learning exercise. In JS i'm very noob.
Can someone review my code and offer constructive criticism?
// noprotect
var targetNumber = Math.floor(Math.random() * 100 + 1);
var userGuess = prompt("Pick a number from 1 to 100 to guess which one I'm thinking about!" + " (6 guesses left.)");
for (var i=5; i>0; i--) {
if (i === 0) {
prompt("Out of guesses!" + " (" + i + " guesses left.)" + " My number was: " + targetNumber);
}
if (isNaN(userGuess) === true) {
userGuess = prompt("That value was not a number! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess < 1 || userGuess > 100) {
userGuess = prompt("That number was not between 1 and 100 inclusive! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess === targetNumber) {
userGuess = alert("You're correct! My number was: " + targetNumber);
}
if (userGuess < targetNumber) {
userGuess = prompt("You're too low, guess again" + " (" + i + " guesses left.)");
}
if (userGuess > targetNumber) {
userGuess = prompt("You're too high, guess again!" + " (" + i + " guesses left.)");
}
}
You're comparing the string value prompt() returns with a number using ===. That's not going to work.
Instead:
var userGuess = parseInt(prompt(...))
It's worth noting that prompt is an extremely clunky way to do this. What would be better is creating a form where you have a proper <input> field and a place to put the responses.
Just to add a quick note before I head home from the office. Your for loop will never allow i === 0condition to pass because the loop only continues if i > 0. You likely want to change this to i >= 0 or adjust your conditions within the loop.

Javascript else if statement error

I have to make a javacript code that satisfy the triangle inequality theorem, which the two smaller sides adds up to be bigger than the largest side. I have to use javascript and use a prompt for users to enter three numbers. I can not ask the user to enter the largest number i have to find it by code. So below is what i got so far, but i keep getting an error at the first else if statement and so i wont run. Any idea whats wrong with my code?
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b, a>=c){
if (b+c>a) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.1" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.1" );
}
else if(b>=c, b>=a) {
if (c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.2" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.2" );
}
}
else {
if (a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.3" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.3" );
}
}
}
// -->
</script>
if statements test a single condition, not multiple ones. Assuming you want to know that both a is greater than or equal to b AND a is greater than or equal to c, you need to use the && operator:
if(a>=b && a>=c)
If it's an OR, it's the || operator:
if(a>=b || a>=c)
There is no such thing
if(a>=b, a>=c){
If you want to check both for true, use:
if (a >= b && a >= c)
If you want to check either or:
if (a > = || a >= c)
But in general, this code looks really bad.
if ((a >= b) && (a >= c))
Search Google for "javascript if" or something like that to learn more.
I've also noticed that your problem is very different from your answer. You say you have to ask for two sides and compute the third, but in your answer you ask for all three and just inform the user if they got the values right...
Do you have to use an if statement.
var input2 = [10, 30, 50, 150];
input2.sort(function(a, b){return b-a});
console.log(input2[0]);
You can run this in firebug console of firefox to see what it does. Corrected my answer.
Thanks guys I know my code is sloppy, but I am just starting out so in time I will get better. Here is the way i fixed the code.
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b && a>=c && b+c>a){
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(b>=c && b>=a && c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(c>=a && c>=b && a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality." );
}
// -->
</script>

Javascript Looping in odd intervals

Ok so I have this problem with a loop assignment I'm working on.
I'm supposed to use a "while" loop for the first 4 loops and a "for" loop for the remaining 15 loops. The problem is the first 4 in the while loop print to the console correctly in sequence like they're supposed to.
The remaining 15 only print to the console in odd intervals IE: "5,7,9,11...."
What's wrong with my for loop?
var currentGen = 1;
var totalGen = 19;
var totalMW = 0;
while(currentGen <= 4){
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + (totalMW = totalMW + 62) + " MW!");
currentGen++;
}
for(currentGen = 5; currentGen < 20; currentGen = currentGen + 1){
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + (totalMW = totalMW + 124) + " MW!");
currentGen++;
}
You have both
currentGen = currentGen + 1
and
currentGen++;
So every iteration you are increasing by 2, not 1. Just do the one or the other.
Because, for loop has its own increment section. You don't have to do it again in the body of the loop
for(currentGen = 5; currentGen < 20; currentGen = currentGen + 1 ) { //incrementing
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + (totalMW = totalMW + 124) + " MW!");
// currentGen++; // Incrementing again
}
That is because you should not have the currentGen++ line inside the for loop. The for loop does that variable increment part.

Categories

Resources