javascript if elseif else not working - javascript

Help! The if/elseif/else code block won't work! When the code reaches prompt "what will you do?" no matter what you type, you get all the alerts. It should come up blank when you type a command that is not in the if blocks, and give you an alert if you did type R, L or M. Typing F should give you no alert.
while (Room = 1) {
var Choice = prompt ("What will you do?");
if (Turn = "Start");
{
if (Choice = "F");
{
Turn = "1";
}
else if (Choice = "R");
{
alert ("You cannot do that...");
}
else if (Choice = "L");
{
alert ("You cannot do that...");
}
else if (Choice = "M");
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...")
}
}

Use == instead of =. A single equals is a variable assignment and evaluates to the result of the assignment. == is used for equality test.

Remove ; from your if and else if statement.
; represents end of statement
Also you can't use = as comparison operation, instead == or ===(strict comparison) as #Andy mentioned.
while (Room == 1) { // Actually your code fails at the beginning itself.
However I would suggest you to use switch for your case.

If you write "=" single equal to means assignment of value to that variable.
So, You should change the "=" Single equalto to "==" Double equalto for conditional purpose.
And If else has no end ";" Semi-Colon required in Javascript. removed it.
I have updated the following please try it.
while (Room == 1) {
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice == "F")
{
Turn == "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...");
}
}
}

You have a semicolon after all your if-elseif-statements. So regardless of what the boolean is inside the if, the if block is empty. Just remove semicolons and you're good to go.
With this:
if(1 == 1);
{
alert('Nope');
}
the block after if-statement is always executed because of the semicolon ending the if.
if(1 == 1)
{
alert('Yup');
}
Works.

Java scrip don't consider single '=' it works with '=='
try
if (Turn == "Start");
Instead of
if (Turn = "Start");

Remove semicolons ; at the end of the if and else if loops
and also compare string by using ==, not =
Replace your code with this one
while (Room = 1) { //here Room is int variable
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice =="F")
{
Turn = "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert ("1" + '\n' + "1" + '\n' + "221" + '\n' + "X");
}
else
{
alert ("You cannot do that...")
}
}

Also, besides using strict comparison I would strongly suggest writing left curly brace just after if(...) not in the new line:
Like:
if(...){
Instead of:
if(...)
{
Reason for that is JavaScript's built-in semi-colon insertion, so sometimes it can produce silent errors or unexpected behavior. In some other programming languages it doesn't matter, but in JavaScript it does.

Related

.includes() Is always returning true

I am trying to make a Wordle type game, I have started on the basics where it is just using the console to tell me weather the letters are correct or not. In the function check letter the first if statement works flawlessly but on the second one when it is checking weather or not the guess and the word both have the same letter just not in the correct spot. But even when the letter is not even in both of the variable it will console "wrong spot" instead of "wrong letter".
const word = "Lucas";
let guessed = prompt("Please Guess The Word");
checkLength()
function checkLength() {
if (word.length == guessed.length) {
console.log("It Worked")
checkLetter(0)
checkLetter(1)
checkLetter(2)
checkLetter(3)
checkLetter(4)
} else {
console.log("It Failed")
guessed = prompt("Please Use 5 Letters");
}
}
function checkLetter(letterPos) {
if (word.charAt(letterPos) == guessed.charAt(letterPos)) {
console.log("Same Letter! " + letterPos)
} else {
let letterW = word.charAt(letterPos)
let letterG = guessed.charAt(letterPos)
if (word.includes(letterW) == guessed.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}
}
The problem is that includes returns true or false, not the index, so when both world and guessed don't include the letter, false == false would return true:
if (letterG !== letterw && word.includes(letterW))
The above condition should work.
First, we should clean up the variables. Then, all that needs fixing is the second if statement. We want to check if letterG exists in word, if not, then it's the wrong letter.
function checkLetter(letterPos) {
let letterW = word.charAt(letterPos);
let letterG = guessed.charAt(letterPos);
if (letterW == letterG) {
console.log("Same Letter! " + letterPos)
} else if (word.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}

Do loop keeps on repeating

So my alternative version of this code is in Java, the logic is fairly similar although in JavaScript the userinput is repeated infinitely rather than carrying until the user loses. This is my working Java code for reference:
int stop =0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
do {
int card;
int upcommingcard;
String userinput;
card= rand.nextInt(13)+1;
System.out.println("Card is "+card);
System.out.println("Higher or Lower?");
userinput = scan.next();
upcommingcard = rand.nextInt(13)+1;
if(!userinput.equalsIgnoreCase("H")&&(!userinput.equalsIgnoreCase("L"))){
System.out.println("Invalid Input ");
}
else if((userinput.equalsIgnoreCase("H")) && (upcommingcard > card)){
System.out.println("Correct!");
}
else if(userinput.equalsIgnoreCase("L") && upcommingcard < card){
System.out.println("Correct!l ");
}
else {
System.out.println("You lost it was " + upcommingcard);
stop=1;
}
}while (stop != 1);
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JavaScript - Not working
var max=13;
var min=1;
var stop=0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is "+card+"... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do{
if((userinput !="H")&&(userinput !="L")){
console.log("Invalid input");
}
else if((userinput ="H")&&(upcommingcard > card)){
console.log("Correct!");
}
else if((userinput ="L")&&(upcommingcard < card)){
console.log("Correct!");
}
else{
console.log("You lost, it was "+ upcommingcard);
stop=1;
}
}
while(stop !=1);
Just to mention also that it registers that the user's input is correct although it fails to continue and just keeps on spitting out the same output until the browser crashes.
EDIT: Thanks for the responses! the loop works perfectly now, my only issue is that the logic is a bit flawed since sometimes I Input 'L' for 8 and upcoming int is 10.. Dispite this I get the Incorrect response.
It's not that your console isn't updating, it's that you never exit your loop if the input is incorrect, and you never offer them the option to try again.
Thus if they are incorrect, the loop will never end, the console won't be updated, and they can't retry.
I would recommend changing the code to the following, to alert the user to try again.
var max = 13;
var min = 1;
var stop = 0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do {
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input!");
userinput = prompt("Card is " + card + "... Higher or lower?");
} else if ((userinput == "H") && (upcommingcard > card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
There are some points I want to make on this:
Your Java and Javascript code logic differs. You had the variables and input reads inside do while in Java but outside in Javascript.
As your prompt right now is outside the loop, it will keep having the same input value everytime and not asking for another one, and will carry on until it's a wrong guess, or forever if it's an invalid input. And the next point worsens your problem:
Your if comparison operators are invalid. What you did, as mentioned in the comments, is a data assignment to userinput and will always return correct
That being said, I corrected it below while adding alert popups instead of console.log only:
var stop = 0;
do {
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input");
stop = 1; //Currently stopping if having invalid input, you can remove this later
} else if ((userinput == "H") && (upcommingcard > card)) {
//Note the '==' above, and also the next one for comparing equal values
console.log("Correct!");
alert("Correct");
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
Now, do compare the JS snippet above with your working Java code you've posted. If you compare again with your JS code, you should be able see what I meant by having different logic.

Checking for no input in control structure

I am writing this basic control structure for a lesson and I am getting some unexpected behavior.
var answer = prompt('what is your age');
if (answer >= 21) {
alert('good to go!');
}
else if (answer < 21) {
alert('sorry not old enough');
}
else if (answer != typeof Number) {
alert('please enter your age as a number');
}
else if (answer === null) {
alert('you did not answer!');
}
On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?
Thanks.
Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""
You need to move the last two checks to the top since "" < 21 is true:
var answer = prompt('what is your age');
if (answer === '') {
alert('you did not answer!');
} else if (isNaN(answer)) {
alert('please enter your age as a number');
} else if (answer >= 21) {
alert('good to go!');
} else if (answer < 21) {
alert('sorry not old enough');
}

Javascript: How can I simplify an if-statement with multiple OR conditions?

Sorry if I've made mistakes writing this post. I'm new here and I don't know how this works, hope I learn quick. I am also new at JavaScript.
So the question is: I have this on my code.elements.js file and I can't make it work.
Does putting this work?
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};
Or do I have to make it by the normal way?, like
if (codePrompt == codeSwitch || codePrompt == codeSwitchBG || codePrompt == codeBlur || codePrompt == codeShowInfo){};
var codeSwitch = 'switch()';
var codeSwitchBG = 'switch(background)';
var codeBlur = 'blur()';
var codeShowInfo = 'showInfo()';
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line.");
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)) {
if (codePrompt == codeSwitch) {
alert("Switching background...");
console.log("Used '" + codeSwitch + "' command.");
} else if(codePrompt == codeBlur) {
alert("Blurring elements...");
console.log("Used '" + codeBlur + "' command.");
} else if(codePrompt == codeSwitchBG) {
alert("Switching background...");
console.log("Used '"+ codeSwitchBG + "' command.");
}else if(codePrompt == codeShowInfo) {
alert("Showing info...");
console.log("Used '"+ codeShowInfo + "' command.");
}
} else {
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
};
});
The "normal" way works the way you probably expect.
However, that if statement is redundant, anyway. You can just skip it:
if (codePrompt === codeSwitch) {
alert("Switching background...");
console.log("Used '" + codeSwitch + "' command.");
} else if (codePrompt === codeBlur) {
alert("Blurring elements...");
console.log("Used '" + codeBlur + "' command.");
} else if (codePrompt === codeSwitchBG) {
alert("Switching background...");
console.log("Used '" + codeSwitchBG + "' command.");
} else if (codePrompt === codeShowInfo) {
alert("Showing info...");
console.log("Used '" + codeShowInfo + "' command.");
} else {
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
}
This is a good use case for a switch, and I would refactor it this way:
var alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeSwitch:
alertMessage = "Switching background...";
break;
case codeBlur:
alertMessage = "Blurring elements...";
break;
case codeSwitchBG:
alertMessage = "Switching background...";
break;
case codeShowInfo:
alertMessage = "Showing info...";
break;
default:
alertMessage = consoleMessage = "Wrong command, try again.";
break;
}
alert(alertMessage);
console.log(consoleMessage);
Because JavaScript has short circuit evaluation and your strings are truthy then you need to use the second approach or what you referred to as "the normal way".
The first way does not work because you end up evaluating the wrong thing. Evaluation works like this:
var result = 0 || "zero" ;
0 is evaluated and determined to be falsy.
"zero" is evaluated as truthy and becomes the result.
var result = "zero" || 0 ;
"zero" is evaluated and determined to be truthy and returned as the result.
0 is not evaluated because short circuit evaluation.
In your original code:
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};
The operator associativity of || is left to right. Parenthesis are evaluated inner to outer.
(codeSwitch || codeSwitchBG || codeBlur || codeShowInfo) is evaluated first. Because of the rules we already discussed the result becomes codeSwitch:
codeSwitch || codeSwitchBG becomes codeSwitch
codeSwitch || codeBlur becomes codeSwitch
codeSwitch || codeShowInfo becomes codeSwitch
So you end up evaluating:
if(codePrompt == codeSwitch)
Which of course is wrong.
You must do it the second way you mentioned:
if (codePrompt == codeSwitch ||
codePrompt == codeSwitchBG || codePrompt == codeBlur || codePrompt == codeShowInfo){};
The way you are implementing this logic I would suggest a switch statement for readability like such:
switch (codePrompt){
case "switch()":
{
//Handle case
break;
}
case "switch(background)":
{
//Handle Case
break;
}
case "blur()":
{
//Handle Case
break;
}
default :
{
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
}
You could also refactor as follows to cut out the if/switch:
var commands = {
'switch()': 'Switching background',
'switch(background)': 'Switching background',
'blur()': 'Blurring elements',
'showInfo()': 'Showing info'
};
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line.");
if (commands.hasOwnProperty(codePrompt)) {
alert(commands[codePrompt] + '...');
console.log("Used '" + codePrompt + "' command.");
} else {
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
}
});
Yes, you have to make it the 'normal' way.
What
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};
does is
1) test all the switches -- returns TRUE if any are TRUE
2) test if codePrompt == TRUE or FALSE.
Based on your code, you can remove that test altogether and simply drop through to your final ELSE.
Another option is use a SWITCH statement, the last ELSE becoming the DEFAULT clause.

Javascript: Is there a limit to "else if" statements?

I am getting value from a text field. I have one if and several else if statement.
The problem the last else if doesn't execute even if the condition is true.
If I change the last else if to if it executes and gives alert. When I change that back to else if the statement doesn't execute. The else if before that is fine as it's firing/executing on a particular condition.
function Valcheck()
{
var txtVal = document.getElementById("sometextField").value;
if(txtVal =="%")
{
alert("% is only allowed with other characters.");
return;
}
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
else if(txtVal.indexOf(",") != -1)
{
alert("Comma or comma separated values are not allowed.");
return;
}
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
{
alert("Please enter % at the end of the value.");
return;
}
else if( txtVal.length > 11 )
{
alert(" Value can't be greater than 11 characters.");
return;
}
}
Please help. Thanks
The problem is that if txtVal.length > 11, then either this is met:
else if(txtVal.indexOf("%") != -1)
or this is met:
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
So that it will never reach the else if( txtVal.length > 11 ). You need to change this:
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
to this:
else if(txtVal.indexOf("%") != -1 && txtVal.indexOf('%') != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
so that it doesn't "capture" the case where txtVal.indexOf('%') == (txtVal.length-1).
There isn't a limit to the number of if statements. The issue is that one of the previous if statements catches the case you're testing.
Go through each if statements for the case your testing and see if it's beging caught by a previous one.
This happens because your else if(txtVal.indexOf("%") != -1) is true (so, second if from the top), but condition for "if" inside it is not true (so it doesn't go to "return".
there is no way that the last 'else-if' be hit:
if the textVal has a '%' in it it will go to the second 'else-if'
and if it does not have '%' it will go to the one before the last one.
so the last if never be hit.
There is no limit to if else nesting. There is a logical barrier to getting to nested if else clauses. Look into using
switch(caseVariable){
case 1: document.write("caseVariable = " + 1);
break;
case 35: document.write("caseVariable = " + 35);
break;
default: break;
}

Categories