Alert message is wrong - javascript

I am currently new to JavaScript and am learning in school! There is an assignment that I am doing by creating a game but the alert keeps popping up with the wrong one. Every time it alerts as "You found a match!" for every card, however this is not supposed to happen. I have been trying to figure this out for the last hour. Thanks
var cards = ["queen", "king", "queen", "king"];
var cardsInPlay = [];
var cardOne = cards[0];
cardsInPlay.push(cardOne);
console.log("User flipped " + cardOne);
var cardTwo = cards[1];
cardsInPlay.push(cardTwo);
console.log("User flipped " + cardTwo);
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
alert("You found a match!");
} else {
alert("Sorry, try again");
}

You have a simple syntax error.
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
By putting your second conditional inside the bracket {, you've made it ineffective. Try this:
if (cardsInPly.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
The condition always goes inside the parenthesis ( ). If it's outside of it, it won't work.
Typing cardsInPlay[0] === cardsInPlay[1]; when they aren't equal is effectively like typing false;. It's technically valid, but doesn't do anything.

I think you ment to put the condition like below:
if (cardsInPlay.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
}

Related

How can I execute continue after break in javascript

I am a begginer to javascript. I was writing some code for my program in which mainly it's loop. It's about you enter your age and it says you should drive or not a simple program but , I wanted to make it repeating itself until the user didn't enters n or N. I wrote a if statement with break and another else - if statement with continue. When i press n it stops but , when I type y it dosen't continue. Plz try to help me Here is the code below:
while(true){
let age = prompt("Enter your age")
if (age>18){
console.log("You can drive")
}
else if (age<0){
console.log("Invalid age")
}
else if (age>100){
console.log("Invalid age")
}
else if (age==18){
console.log("Come to our office")
}
else{
console.log("You cannot drive")
}
let choice = prompt("Type y or Y to run again type n or N to exit")
if(choice == "n" || "N"){
continue
}
if (choice == "y" || "Y")
break
}
Your if conditions are strange, you say if(choice == "n" || "N"), which means, in words "go in the next block if the variabe choice is 'n' or if 'N'". I'm guessing saying if("N") gets interpreted as true, since it's not null.
You should write, explicitly, if(choice === "n" || choice === "N").
Also, as phuzi said in the comments, continue makes the code restart the loop with the next iteration, while break makes the code go out of the loop. It seems you have them backwards

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.

How to avoid to repeat a variable

Hi I'm new to javascript and was wondering if the community could help me in re-writing more logically the following snippet:
var userAnswer = prompt("Are we there yet?")
while ((userAnswer != "yes" && userAnswer != "yeah") && (userAnswer.indexOf("yes") === -1)) {
var userAnswer = prompt ("Are we there yet?")
}
alert ("Yuppie we made it!")
the part that I think could be improved is in the while loop when I have to repet the entire string of var userAnswer = prompt....
there must be a dry way of doing it. Any help would be much appreciated!
Since you want to run ask for a value at least once you could use do-while instead. You could define variable within the do block, it still will be hoisted.
do {
var userAnswer = prompt("Are we there yet?")
} while ((userAnswer != "yes" && userAnswer != "yeah") && (userAnswer.indexOf("yes") === -1))
alert("Yuppie we made it!")
PS. I kept the condition assuming it works for you.
Instead of prompt to enter free text use confirm that will return true or false:
while (!confirm("Are we there yet?"));
alert("Yuppie we made it!")
A way of doing it without using a while loop.
var answer = prompt ("Are we there yet?", "YES or NO")
answer != "yes" ? prompt ("Are we there yet?", "YES or NO"): alert("We made it !!");

Whats wrote with this break;

After adding break, my code no longer works.
alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }
You have a few syntax errors in your JavaScript. You are missing out on a curly brace. The break statement needs to be after the alert statement. See the following snippet after the fixes and try to learn your mistakes.
alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {
while(true) {
//var b = prompt("Are you ready to enter this game?");
if(a == "yes") {
alert("Entering");
break;
}
}
}
break; alert("Entering");
It's to late to alert after breaking as it immediately exits the loop and doesn't execute instruction after itself there.
I believe you intend to prompt the user repeatedly until he answers yes. In that case, use this code:
alert("Warning: Game is made for the age of 18 and over.");
let response = "";
while(response !== "yes") {
response = prompt("Are you ready to enter this game?");
}
alert("Entering");

How can I set an empty alert

I have made a little game in Script. That's sort of arithmetic game. I asked 2+2-3=? and user have to give the answer. If the answer is right than alert will show congratulations and if answer is wrong then you are higher or lower than actual answer. But now I want to add another alert if someone not answering this question and leave the prompt empty and press enter than another alert will be display like You are looser. My question is; how can I set the value empty and alert. Here is what I tried and it didn't work. Please see the code below:
<script type="text/javascript">
var number = prompt("count these numbers: 2+5-10+8=?");
if (number == 5) {
alert("Congratulations Your Answer is Correct");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
} else if (number == "null") {
alert("You are looser!");
}
</script>
I would parse the number so it's actually a Number type, instead of relying on the == to coerce the value for you. Then, you could check for NaN with the isNaN function, or better yet, leave off the if completely and just make it an else:
var number = parseInt(prompt("count these numbers: 2+5-10+8=?"), 10);
if (number === 5) {
alert("Congratulations! Your answer is correct.");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
} else {
alert("You are a loser!");
}​
http://jsfiddle.net/KebNN/
Just compare it to an empty string:
if (number == '') {
// ...
Also, if you want to alert the same message on "Cancel" clicks, you can simply check whether number evaluates to false:
if (!number) {
// ...
Use (answer == null || answer == undefined || answer == '')
try:
} else if (number == "" || isNaN(number)) {
alert("You are looser!");
}
I'm not sure I understand the question, but is this what you're looking for?
alert("");
If the user presses cancel on a prompt, the value will be null. By comparing it with ===, we make sure the answer isn't 0 (0 == null is true).
<script type="text/javascript">
var number = prompt("count these numbers: 2+5-10+8=?");
if (number === null) {
alert("You are loser!");
} else if (number == 5) {
alert("Congratulations Your Answer is Correct");
} else if (number > 5) {
alert("Your answer is a little higher.");
} else if (number < 5) {
alert("Your answer is little lower than actual answer.");
}
</script>​
You have accounted for all of the possible results except for null you could just add a else at the end of the first if statement as a catch all.. I.E. if the user leaves it blank or enters an invalid character.
if( number == 5 ) {
alert( "Congratulations Your Answer is Correct" );
} else if ( number > 5 ) {
alert( "Your answer is a little higher." );
} else if ( number < 5 ) {
alert( "Your answer is little lower than actual answer." );
} else {
alert("You are looser!");
}
.....

Categories

Resources