comparing against a string - javascript

I have some JavaScript code that creates a different message depending on various factors in the response object from an Ajax request. For example
if (response.correct_guess === true){
message = "your guess was correct
}
If the user wins the game, the 'won' key is set to 'won'
won: "won"
and I'm therefore hoping to set the message like this
else if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
However, this 'else if' isn't getting triggered
I also tried "==" (i.e. two equal signs instead of three). Can you explain what I'm doing wrong?

What your code means:
if (response.correct_guess === true){
message = "your guess was correct
}else if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
}
If the guess is correct, message = "your guess was correct, and that's it. If the guess was not correct, AND if the user won, message = "You finished with" + response.seconds + "left on the clock."
You forget that if control enters the first if, it will never reach the second else if. In an if-elseif chain, the first if/elseif block control enters is the only one it will enter . I don't think you want that. You probably want:
if (response.correct_guess === true){
message = "your guess was correct
}
if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
}

Related

Calling of functions not working properly

I am working on a computer science project, I need to make a Wheel of Fortune game - basically, get a random word, show blank spaces, and have the player(s) guess the letters to form the word. Right now, I've got the parts where the word is chosen, hidden (switching the letters for blank spaces), and shown. Now, I am on the part of enable player turns to start guessing the letters. I have set up a button to call a function which calls other functions (each turn is broken down into multiple parts, such as asking for a guess, checking what type of guess it is, and checking if that guess is in the word). For some reason, this bigger function is, when calling them, only calling the first function, and spamming that single function. Why is it not going down the list of functions and calling each in order?
Here is the code that relates to that part:
function player1() {
console.log("Player 1 is going.");
nowGoing = 1;
player1Elements.style.display = "block";
alert(player1Name + " it is your turn. What do you guess?");
prompt();
checkGuessType();
checkGuess();
}
function prompt() {
console.log("Prompting");
var playerGuess;
playerGuess = prompt("What letter would you like to guess?");
checkGuessType(playerGuess);
}
function checkGuessType(playerGuess) {
console.log("Checking");
if (playerGuess.length > 1) {
console.log(player1Name + " guessed a word.");
} else if (playerGuess == "a" || playerGuess == "e" || playerGuess == "i" || playerGuess == "o" || playerGuess == "u") {
console.log(player1Name + " guessed a vowel.");
} else {
console.log(player1Name + " guessed a consonant.");
}
}
All that appears in the console (the console.logs are exactly for this purpose) are 6000 lines saying "Prompting", not "Prompting" and "Checking". If there is any more code I should show, please let me know!
If anyone could help me out, that would be great!
Edit: I tried changing the code to the following (basically changing to a global variable), but it still didn't work. I'm not sure why, as the same thing happens.
function player1() {
console.log("Player 1 is going.");
nowGoing = 1;
player1Elements.style.display = "block";
alert(playerName1 + " it is your turn. What do you guess?");
prompt();
checkGuessType();
checkGuess();
}
function prompt() {
// console.log("Prompting");
playerGuess = prompt("What letter would you like to guess?");
}
function checkGuessType() {
console.log("Checking");
if (playerGuess.length > 1) {
console.log(playerName1 + " guessed a word.");
} else if (playerGuess == "a" || playerGuess == "e" || playerGuess == "i" || playerGuess == "o" || playerGuess == "u") {
console.log(playerName1 + " guessed a vowel.");
} else {
console.log(playerName1 + " guessed a consonant.");
}
}
The reason that "Prompting" is appearing over and over is that you provide playerGuess as the argument for checkGuessType in prompt but playerGuess is just another call to prompt so it starts recursing. However, prompt never returns any value under any condition, so the recursion will never resolve to a value causing the stack of function calls to collapse and execute the call to checkGuessType, so you never see a repetition of the console.log in checkGuessType.
EDIT
After your edit I just wanted to point at what I think the problem is directly:
function prompt() {
// console.log("Prompting");
playerGuess = prompt("What letter would you like to guess?");
}
Within the scope of your function, prompt just refers to the function itself. This is causing a recursion. That recursive stack will never end because nothing returns from prompt, thus eventually causing a stack overflow error. If you don't mean to be starting a recursive stack, you need to rename your prompt function to something other than what the built in prompt function is called.

2 errors in my javascript random number-guessing game

This is the first app I have ever written. I have seen a million random number-generating games here, javascript and otherwise, but none had the problems I'm having. I apologize for my ignorance, but when I know what I'm doing wrong, this will go a long way toward my understanding of javascript and coding in general. I'm just playing in the browser console as of now.
I've done this with a for loop, but I wanted to try another option and use a decrement counter. I've tried using the if/else stuff from the inner function inside the while loop. The code looks right to me.
const guessingGame = (tries) => {
const answer = Math.floor(Math.random() * 11)
let guess = null
let status = "playing"
function makeGuess() {
if (guess === answer) {
status = "won"
} else if (tries === 0) {
status = "lost"
} else {
tries--
if (tries === 1) {
console.log(tries + ' guess left')
} else {
console.log(tries + ' guesses left')
}
}
}
while (status === "playing") {
if (!guess) {
guess = prompt('Guess a number between 1 and 10')
makeGuess()
} else if (guess > answer) {
guess = prompt('Lower')
makeGuess()
} else if (guess < answer) {
guess = prompt('Higher')
makeGuess()
} else {
break
}
}
console.log("Game Over. You " + status + "! The answer was " + answer + ".")
}
This game should invoke/launch with one argument, the number of tries allowed. If I correctly guess the answer, the console log at the end should include status = "won". But when I win, it includes status = "playing".
When I guess wrong "tries" number of times, I should lose. But when I see "0 guesses left" in the console, the game gives one more guess, and I can take it, effectively making tries -1, I think. When I make one additional wrong guess, status correctly changes to "lost" and the final console message is correct.
You checked tries === 0 before tries--, that's why you get 0 guesses left. You should decrement before checking.
The guess is actually a string not a number, so guess === answer never true. The next iteration after you guessed correctly, it falls into else{break} with the status still playing. You either want Number(guess) === answer or just guess == answer.
By Math.floor(Math.random() * 11) you are actually generating 0-10. You want Math.floor(Math.random() * 10) + 1 for 1-10. Just remember Math.floor(Math.random() * n) gives you n possible outcomes, which happens to be an integer in the range [0,n). Then do whatever calculation you want to map it to your desire output value.
const guessingGame = (tries) => {
const answer = Math.floor(Math.random() * 10) + 1
let guess = null
let status = "playing"
function makeGuess() {
tries--;
if (guess === answer) {
status = "won"
} else if (tries === 0) {
status = "lost"
} else {
if (tries === 1) {
console.log(tries + ' guess left')
} else {
console.log(tries + ' guesses left')
}
}
}
while (status === "playing") {
if (!guess) {
guess = Number(prompt('Guess a number between 1 and 10'))
makeGuess()
} else if (guess > answer) {
guess = Number(prompt('Lower'))
makeGuess()
} else if (guess < answer) {
guess = Number(prompt('Higher'))
makeGuess()
} else {
break
}
}
console.log("Game Over. You " + status + "! The answer was " + answer + ".")
}
guessingGame(5);
The result of prompt is a string; thus, guess is a string. The result of Math.floor is a number, so answer is a number.
> and < are coercing operators: if one of the operands is a number, the other is converted into the number, as well. This means guess < answer and guess > answer work as you hope it does.
However, you've apparently heard people say "never use ==, always use ===" and taken it to heart. The reason for the saying is == is also a coercing operator, and as a consequence sometimes things that don't look equal end up being equal. However, here you actually needed to use the coercing ==, because 1 == '1' (even though 1 and '1' are different types), but the strict 1 === '1' ends up being false!
Thus, you first check if guess is strictly equal to answer. Since their types are different, it is impossible, so you move on. You check if guess is above the answer, then you check whether it is below the answer, both of those return false as well. The only remaining option is to break from the loop - and "winner" never gets printed.
Beside this, your biggest problem is actually logic. The placement of different tests and actions is somewhat questionable. For example, one would expect that testing whether guess is equal to the answer would be right next to the test to see if it is bigger or smaller. The test for tries would be most at home right at the while loop; but you have an infinite loop, and an independent test for tries. You enter the first guess with a unique prompt, but it is inside an infinite loop, despite the fact it can only ever happen once. You have a function called makeGuess, but the function does two or three different things, none of which is actually making a guess.
Rather than start working on code right away, then fixing problems as they pop up, try to imagine first what the flow would be. How would a human do it? Then write code.
Here's the basic idea for the same game:
answer = imagineAnswer()
guess = askForFirstGuess()
status = "lost"
while (--tries) {
if (guess > answer) {
guess = askForHigherGuess()
} else if (guess < answer) {
guess = askForLowerGuess()
} else {
status = "won"
break
}
}
reportGameEnd(status)

Stop a 'falsy' alert after a correct prompt in JavaScript

After answering the prompt correctly, the alert-message for wrong answer still appear after the right answer is given. I don't seem to find why nor how to terminate the second alert.
var userResponse = prompt("Hello, please enter the capital of Massachusetts?");
if(userResponse === "Boston") {
alert("Yes! Boston is the right answer");
};
if(userResponse === "Albany"){
alert("I am sorry, but Albany is rather the capital of NY");
}
else {
alert("I am sorry, but" + userResponse + " is not the right answer.");
};
Bad formatting / code style and a missing else:
var userResponse = prompt("Hello, please enter the capital of Massachusetts?");
if (userResponse === "Boston") {
alert("Yes! Boston is the right answer");
} else if (userResponse === "Albany") {
alert("I am sorry, but Albany is rather the capital of NY");
} else {
alert("I am sorry, but " + userResponse + " is not the right answer.");
}
Also note semicolons (;) are not necessary after code blocks ({}). In fact, in your case, one would have broken your if-else if chain.
Your code works! I think you must be simply typing it in wrong since it is case sensitive. I would add this so that it is not case sensitive:
if (userResponse === "Boston" || userResponse === "boston") {
Now you can type boston instead of only being able to type Boston. My recommendation is to never make the answer only case sensitive! In this case, it will say I am sorry, but boston is not the right answer., when it is totally correct
And make sure to add else on the second possibility as #AurelBily pointed out!

Guessing game, 1 to 100 using do/while loop and if/ese if conditional statement

I am trying to make a guessing game with simple java script. the professor gave us a guide, but i am still a bit confused. Based on the guide, we are to use a do/while loop, and within that loop, use the if/else if conditional statement, here is what i have so far.
i've tried changing it so many times, and all i end up with is a never ending loop, even after the number is guessed, it doesnt stop
<body>
<p>
I'm thinking of a number between 1 and 100, try to guess it! </br>
<script>
var number = Math.floor(Math.random() * 100 + 1)
//guess variable to store the guessed number by user
var guess
//output to store output to the user
var output
//if the user guessed the number or not, initialize it to false
var guessed = false
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt ("Think of a number between 1 and 100, what is your number?");
document.write ("You guessed the number " + guess + "<br/>");
if (guess > number) {
document.write ("You guessed too high, think smaller" + "<br/>");
guessed = false
}
else if (guess < number){
document.write ("You guessed too low, think bigger" + "<br/");
guessed = false
}
else {
alert("You guessed the right number!")
guessed = true}
}
while (guessed = false)
</script>
</p>
</body>
You're missing a ton of semi-colons which should be added though your code will still run without them. And like everyone else said you are assigning guessed to false at the end of your do while loop, therefore it will never break out. To check a condition you should use 3 equal signs (this is strict comparison). More on that here. It is debatable if document.write should be used. Reason for that can be found here. Also, when testing your code it worked intermittently, so I added a div with the id of hints. Then I grabbed that element with var elHints = document.getElementById('#hints'); Then to add content to the element hints simply do elHints.textContent += .... The plus equals (+=) adds content to the element without overwriting existing content. In css I added a style to #hints: white-space: pre-line; this allows line breaks (\n) to the div when adding content using textContent. More on that here.
Here is the full javascript code:
var number = Math.floor(Math.random() * 100 + 1);
//guess variable to store the guessed number by user
var guess;
//output to store output to the user
var output;
//if the user guessed the number or not, initialize it to false
var guessed = false;
var elHints = document.getElementById('hints');
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
elHints.textContent += "You guessed the number " + guess + '\n';
if (guess > number) {
elHints.textContent += "You guessed too high, think smaller" + '\n';
guessed = false;
} else if (guess < number) {
elHints.textContent += "You guessed too low, think bigger" + '\n';
guessed = false;
} else {
alert("You guessed the right number!")
guessed = true;
}
}
while (guessed === false);
And here's the jsfiddle.
I believe that you are missing a semi-colon here :
while(guessed == false);
This is just an requirement specific to the do-while loop and does not occur in the syntax for other loops.
In your condition at while(guessed = false) you use one equal-signe (=), witch is forever true. you must write (guessed == false) or (guessed === false). for trying i would do ist so:
I'm thinking of a number between 1 and 100, try to guess it!
<script type="text/javascript">
var number = Math.floor(Math.random() * 100 + 1);
// Just for Test
document.getElementById('test').innerHTML += '<br />' + number;
//guess variable to store the guessed number by user
var guess;
//output to store output to the user
var output;
//if the user guessed the number or not, initialize it to false
var guessed = false;
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
document.getElementById('test').innerHTML += '<br />' + "You guessed the number " + guess;
if (guess > number) {
document.getElementById('test').innerHTML += '<br />' + "You guessed too high, think smaller";
guessed = false;
}
else if (guess < number) {
document.getElementById('test').innerHTML += '<br />' + "You guessed too low, think bigger";
guessed = false;
}
else {
alert("You guessed the right number!")
guessed = true;
}
}
while (guessed == false)
</script>
Your code has some issues.
First of all you need to change while (guessed = false) into while (guessed === false) because it should be a comparision, hence you have to use a comparator.
Secondly, you are using document.write(). This will not work, because the HTML won't change until the user breaks out of the loop. It would be a good idea to use alert() instead. Here is a working example:
var number = Math.floor(Math.random() * 100 + 1)
//guess variable to store the guessed number by user
var guess
//output to store output to the user
var output
//if the user guessed the number or not, initialize it to false
var guessed = false
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
if (guess > number) {
alert("You guessed too high, think smaller");
guessed = false
} else if (guess < number) {
alert("You guessed too low, think bigger");
guessed = false
} else {
alert("You guessed the right number!")
guessed = true
}
}
while (guessed === false)

String comparison returns false. Strange javascript behaviour with jQuery mobile

I started to create a todo list with jQuery mobile in order to learn it better. I'm listening to the events coming from the buttons of a menu like this:
me.selectedTarget = me.menuNode.find(".ui-btn").first();
me.menuNode.on("click", ".ui-btn", function (e) {
var target = $(e.currentTarget)
,targetText = target.text();
console.debug("Click on'", targetText,"'" );
if(target === me.selectedTarget) return;
if(targetText == "View To Do "){
core.pub("view:todo");
} else if(targetText == "View Done ") {
core.pub("view:done");
} else {
me.selectedTarget.click();
}
me.selectedTarget = target;
});
The variable targetText has one extra " " space at the end for some reason. I have 3 buttons, but the third one is a bit special - not relevant anyway -.
My problem is that I'm always getting on the last else clause. targetText never get's to be equal to "View To Do " or "View Done ".
Why isn't "View Done " == "View Done "? ~X(
The comparison is failing because the strings are not the same. So the question really is why are they not the same? Apparently the space in one of the strings is not the standard space character (Unicode has more than one space), or one of the strings has an invisible character in it (Unicode has those, too).
So to find out what's going on, I'd do this:
var index;
for (index = 0; index < targetText.length; ++index) {
console.log("char " + index + ": " + targetText.charCodeAt(index));
}
...and the same with your string literal in your code (not retyping it, but moving it into a local and then outputting that; since if you retype it, you'll presumably type the normal space). Compare the sequences of character codes and you'll find the discrepancy.

Categories

Resources