While loop not displaying correct result Javascript - javascript

I'm working on a project for one of my classes where I need to use the users input to redirect them to a website. It requires that the users choice be validated using a loop, so I've chosen to use a while loop to check for if the users input differs from what it should be and if it is, the user is prompted to re-enter their answer. Here's the code:
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice != 1 || 2 || 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice = 1) {
alert("you chose 1")
}
else if (websitechoice = 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
So far it was just a quick mock up I made to check if it would work, but every time I try and run it, I always get back "you input an incorrect value" even when inputting 1, 2, or 3, and so far nothing I've tried had differed the results. if anyone could help I'd really appreciate it, thanks

You're using a definition in the if statement, in that you're telling the code that websitechoice is now equal to that number. You should use a comparator like so
if (websitechoice == 1) {
alert("you chose 1")
}
else if (websitechoice == 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
For your while statement, you should change it to and statement, because you only want to run the code when it's not equal to one and not eqaul to two and not equal to three
while (websitechoice != 1 && websitechoice != 2 && websitechoice != 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
You could also just say, if websitechoice > 3 then do the alert process

There are many flaws in your code. First of all, you should use AND operator instead of OR operator. Also, you need to break the comparison as beloe demonstrated.
Secondly, you have used assignment operator ( = ) in the if else statement. You need to use comparison operator ( == or === ) to compare otherwise it will return 1 everytime.
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice !== 1 && websitechoice !== 2 && websitechoice !== 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice === 1) {
alert("you chose 1")
}
else if (websitechoice === 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
Also, it will be easy to debug if you put your code in the snippet. Seems like you are quite new to developer community. Welcome to coder community !

The != has precedence over the || operator 1 so:
websitechoice != 1 || 2 || 3
will always evaluate to:
(websitechoice != 1) || 2 || 3
which is not what you want...
another issue is that:
websitechoice = 1
is an assignment not a comparison.
To fix your code without changing its structure:
var websitechoice;
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
while (websitechoice !== 1 && websitechoice !== 2 && websitechoice !== 3) {
alert("you input an incorrect value")
websitechoice = parseInt(prompt("Which website would you like to go to? \n 1. google \n 2. gmail \n 3. youtube"))
}
if (websitechoice === 1) {
alert("you chose 1")
}
else if (websitechoice === 2) {
alert("you chose 2")
}
else {
alert("you chose 3")
}
A cleaner way to check if your input is one of a list of values would probably be:
[1,2,3].includes(websitechoice)
which is cleaner and can scale easily to more values.
I've also replaced the == operators with ===, don't use == in JS unless you know what you are doing. 2

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

Why does do-while not evaluate logical &&?

Here is a simple code snippet where I am ensuring the user input is a number and is between 1-3
do{
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
}while(isNaN(choice) && (choice === 1 || choice === 2 || choice === 3));
While debugging I see the debugger does not even evaluate the part after && where I am keeping a check on the input to be among 1, 2 or 3
Weirdly enough, the do-while construct works fine if I just have :
do{
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
}while(isNaN(choice));
Can someone tell me what am I missing here or doing wrong?
As your code looks now, you are looping as long as it's not a number and it's either 1, 2, or 3. Since those three are all valid numbers, the overall condition can never be true - if it's not a number then it won't be 1, 2 or 3, and if it's 1, 2 or 3 it won't be "not a number" (since it's a number).
From what you wrote, you want to keep looping if it's not a number or not one of those three:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (isNaN(choice) || !(choice === 1 || choice === 2 || choice === 3));
(I changed && to || and added a ! before the second part of the condition.)
However, since you are limiting it to three exact options anyway, you don't even need to check for NaN anymore, because as mentioned before, if it's 1, 2 or 3 it means it's not NaN anyway:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (!(choice === 1 || choice === 2 || choice === 3));
This becomes a bit easier to read by getting rid of the negation in the front, replacing === by !== and || by &&:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (choice !== 1 && choice !== 2 && choice !== 3);
An alternative way to simplify the previous code is to create an array with valid values and loop as long as this array doesn't include the actual input number:
do {
var choice = parseInt(prompt("Please select one of the following:\n1.ROCK\n2.PAPER\n3.SCISSORS\n[NOTE: Choose your selection by pressing a number between 1,2 or 3.]"));
} while (![1, 2, 3].includes(choice));
When the first statement of the while loop is false the compiler doesnt compile the other statements after && here in this example (choice === 1 || choice === 2 || choice === 3) because it doesn`t matter what the other statements result is. The while loop is not executed at all.
This is compiler optimation (Short-circuit evaluation) for more information look at this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
Assume that when you prompt a non-nan value e.g. a number, isNaN evaluates false, thereby going into short-circuit evaluation. However, I think you want to accept one of 1,2, or 3 values. So shouldn't it be like !(choice === 1 || choice === 2 || choice === 3)? If one of them equals that value, no need to loop again.
A less complicated approach (avoiding parseInt, isNaN and multiple boolean checks) may be (snippet for the whole game ;):
Play it here
document.querySelector('button')
.addEventListener( 'click', () => location.reload() );
let choices = ['ROCK', 'PAPER', 'SCISSORS']
let choice = 0;
while ( !choices[+choice-1] ) {
choice = prompt(
`1. ROCK; 2. PAPER; 3. SCISSORS`, `Enter 1, 2 or 3`);
}
const values = {
yours: choices[choice-1],
mine: choices[Math.floor(Math.random() * 3 )]};
const tie = values.yours === values.mine;
const iWin = values.yours === 'SCISSORS' && values.mine === 'ROCK' ||
values.yours === 'ROCK' && values.mine === 'PAPER' ||
values.yours === 'PAPER' && values.mine === 'SCISSORS';
console.log(`your choice: ${values.yours}, against: ${values.mine}. ${
tie ? 'Tied...' : iWin ? 'You lost' : 'You win!'}` );
<button>Again...</button>

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

why does my code return ReferenceError: tea is not defined when i choose tea? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i'm currently coding some javascript, and i'm stuck. here's the code:
var options = confirm ("Here's our menu. we have chicken, rice, eggs (boiled, fried or served uncooked), meat (choose your type of meat (you can take it raw, sauced or pre-cooked)), tea, coffee, some sweets (galaxy, all types (crunchy, hazelnut, plain, almond, caramel and flutes (flutes with 1-pair and 2-pairs)), and we have grocery if you need.")
var choice = prompt ("Choose the item that you want.")
var addon = prompt ("Would you like any additional thing to your order?")
var amount = prompt ("How much do you want from the item you requested?")
var addonAmount = prompt ("How much additional items would you like for your order?")
switch (choice && addon && amount && addonamount) {
case 'chicken':
if (choice === "chicken" && addon === "no" && amount > 0 && addonAmount > 0) {
console.log("Okay. " + amount + " " + choice + "with " + addonAmount + addon + " coming right up!")
} else {
console.log("Sorry, but i didn't hear your request properly.")
}
case 'rice':
if (choice === rice && addon === "no" && amount > 0 && addonAmount > 0) {
console.log("Okay. " + amount + " " + choice + "with " + addonAmount + addon + " coming right up!")
} else {
console.log("Sorry, but i didn't hear your request properly.")
}
case 'tea':
if (choice === tea && addon === "no" && amount > 0 && addonAmount > 0) {
console.log("Okay. " + amount + " " + choice + "with " + addonAmount + addon + " coming right up!")
} else {
console.log("Sorry, but i didn't hear your request properly.")
}
default:
console.log("Sorry, but the items you requested was not found.")
}
*note that the code is still flawed
EDIT: i revamped the code, but it still flawed, and i need help.
soo, what's the error making line in the code, and how could i fix it? thanks. any suggestions on code optimization would be appreciated!
There are a few things that stand out to me to help you get rid of your bugs. I'm not clear on what logic you want to follow for your switch, but I will point out some things you should change to avoid behavior that you might not be expecting.
First thing is in the switch statement signature has a series variables separated by && operators. This will cause the last variable to be evaluated to become your 'case.' It looks like the your 'case' will be addonAmount; however it looks like you might just want it to be choice. You should just put choice in the signature by itself because if any of those values are false, it will just return false instead.
It should look like this:
switch (choice) { ... }
(also, you have a typo: addonamount should be addonAmount but if you just take that out it won't matter anymore)
Secondly, you need to make sure that you put a break; after every case otherwise it will run the next case even if the criteria has not been met.
That should look like this:
case 'chicken':
if (choice === "chicken" && addon === "no" && amount > 0 && addonAmount > 0) {
console.log("Okay. " + amount + " " + choice + "with " + addonAmount + addon + " coming right up!")
} else {
console.log("Sorry, but i didn't hear your request properly.")
}
break; //make sure you do this at the end of every case block
case 'rice':
It looks like you are referencing tea as a variable and not a string here:
if (choice === tea && addon === "no" && amount > 0 && addonAmount > 0) ...
Your error is saying that tea is not defined is because you do not have a variable named tea defined. tea should be a string, not a variable which means that you surround it with quotes. When you leave a series of letters in JavaScript without quotes around it, it tries to parse it as a variable unless it is a special JavaScript keyword (like function, var, switch, etc)
Try this instead:
if (choice === "tea" && addon === "no" && amount > 0 && addonAmount > 0) ...
Also, you have the same error for the "rice" selection:
if (choice === rice && addon === "no" && amount > 0 && addonAmount > 0)...
Should be:
if (choice === 'rice' && addon === "no" && amount > 0 && addonAmount > 0)
More information on switch statements can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
If your code still is not doing what you expect, it probably lies in the if statement signature where you are doing a series of && operators again. What happens is that it will only enter into that if block if all those conditions return a truthy value.
Just a last note that you should be consistent with your choice of quotes. If you want to do single or double, it doesn't matter as long as you use the same ones (or if you work at a company it should be the same as the rest of the codebase).
I hope those changes help you get closer to your goal!

Javascript skips function

I an working on a project for an Introductory Programming class so I'm using basic javascript. This is our first project with functions and for some reason I can't seem to make it work. I called all my variables and created the function before the program starts but for some reason it skips over running the function in my program. Any help would be appreciated.
This is just the beginning of my program, I don't wanna write the rest of the code until I figure out why this part is broken, thats why the program doesn't do anything but close the window if it doesnt pass the tests.
// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";
function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3) {
if (numTrees == 5, 10) {
answer = "yes";
} else if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
}
}
if (answer == "no") {
alert("You have entered an incorrect number too many times.\nThe Program will now end.");
window.open('', '_self', '');
window.close();
} else if (answer == "yes") {
return;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees); {
document.write("<br/> <br/>" + "End of Program.");
}
You have;
if(numTrees == 5, 10)​
The erroneous comma is causing the if to evaluate the truthy expression 10 so its always passing the test, to test for 5, 6, 7, 8, 9 or 10;
if(numTrees >= 5 && numTrees <= 10)
The way you are using the comma in this line has a special meaning:
if(numTrees == 5, 10)​
Essentially what this does is returns the value of 10 (the second operand) when cast to a boolean, which is not 0, so it is true.
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comma_Operator
You probably meant to use OR (||):
if(numTrees == 5 || numTrees == 10)​
Or check numTrees against a range:
if(numTrees >= 5 || numTrees <= 10)​
On a side note, in javascript it is recommended that you always use identity comparison (===) instead of regular comparison (==):
if(numTrees === 5 || numTrees === 10)​
if(numTrees == 5, 10)​ doesn not mean If numtrees is equal to 5,6,7,8,9, or 10
change it to
if(numTrees >= 5 || numTrees <=10)​
if (numTrees == 5, 10) {
answer = "yes";
}
This is an odd-looking construct that I've never seen before. I'm assuming you believe it means "is numTrees within the range 5 to 10?", but that's not the case. Without checking, I think it essentially means you're checking two things at once:
is numTrees equal to 5?
is 10? (this essentially means "is 10 not 0", which of course is always true).
Since the 2nd condition you're checking is always true, you're always setting answer to "yes". As a result, your loop always runs exactly once - it starts up, checks answer is "no", sets answer to "yes", and that immediately stops the loop.
You need to change your condition to if(numTrees >= 5 && numTrees <= 10)
What you want is something more like this:
if (numTrees < 5 || numTrees > 10) {
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
counter + 1;
} else {
answer = "yes";
}

Categories

Resources