Require user to choose 'boy' or 'girl' - javascript

I am trying to get my user to respond to the question "are you a boy or a girl?" with one of those two choices and force them to choose one or the other.
I think I am heading in the right direction but whenever i run my code, it hiccups if choosing the second option.
What am i doing wrong?
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (gender !== ("boy" || "girl")) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}

Personally I like
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (["boy", "girl"].indexOf(gender) == -1) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}

The proper condition would be
while (gender !== 'boy' && gender !== 'girl'){
That's because ("boy" || "girl") will always end up as "boy", therefore the while will look like while(gender !== 'boy'). The || in this case is called a "default" operator, a clever use of the logical OR . If the value on the left side is truthy, it will use the left side value. Otherwise, it will evaluate (hence "default") the right side.

Related

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

Can I use a while loop to validate a prompt input?

I am doing a project in a Javascript course and I need to check the conditions to make sure that the correct information is being passed in.
I am trying to learn to think like a programmer so my first solution only checked the conditions once. Seeing that as a problem I tried to think of a way to keep checking the conditions until all the information was correct. I am trying to use a while loop but I am not able to get it working.
My logic is as long as lastname is not equal to NaN OR lastname.value is less the 4 char long OR lastname is equal to null. Keep asking for there last name. If any of those conditions are true keep asking for there last name until they are all false.
I want to use a while loop for the gender prompt to but I am not sure what I am doing.
I am new and not really sure where I went wrong in this?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Conditionals</title>
<script>
/*
Write the greetUser() function that prompts the user
for his/her gender and last name and stores the results
in variables.
For gender:
If the user enters a gender other than "Male" or "Female",
prompt him/her to try again.
For last name:
If the user leaves the last name blank, prompt him/her to
try again.
If the user enters a number for the last name, tell the user
that a last name can't be a number and prompt him/her to try again.
After collecting the gender and last name...
If the gender is valid, pop up an alert that
greets the user appropriately (e.g, "Hello Ms. Smith!")
If the gender is not valid, pop up an alert
that reads something like "XYZ is not a gender!"
*/
function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
if (gender != "Male" && gender != "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname != NaN || lastname.value < 4 lastname == null); {
lastname = prompt("Please try again. What is your last name?");
}
}
</script>
</head>
<body onload="greetUser();">
<p>Nothing to show here.</p>
</body>
</html>
function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
while (gender !== "Male" && gender !== "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname === '' || lastname.length < 4 || lastname === null) {
lastname = prompt("Please try again. What is your last name?");
}
}
greetUser();
I made little fixes to your code.
Your while loop has incorrect logical operators, this the correct version: while (lastname === '' || lastname.length < 4 || lastname === null) Further, you were comparing lastname !== ''.
For the gender prompt you need to execute a while loop while (gender !== "Male" && gender !== "Female").
Hope it helps!

Why doesn't this code work? Javascript if statement, else if statement

This is a javascript code, and I wanted to make it like:
if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question."
But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question."
help!
var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}
This line:
else if(id || "yes" || "no")
doesn't test whether id has the values "yes" or "no" in it. It tests if id is truthy*, or "yes" is truthy (it is), or "no" is truthy (it is). So the overall condition will always be true, regardless of the value of id.
Since you're using else if, you don't need to check for "yes" or "no" at all at that point — if you got there, you know id doesn't have either of them in it. So just
else if (id)
...will tell you that id has something in it, but it wasn't "yes" or "no" (because you already handled them).
* "truthy" - Coerces to or is treated as true when coerced to boolean or used in a logical operation. It's the other side of "falsy," which coerces to or is treated as false in the same situations. The falsy values in JavaScript are 0, "", null, undefined, NaN, and of course, false. All other values are truthy (including " ", FWIW).
Ok, so the problem is in line
if(id || "yes" || "no")
You check whteher the id variable exist or string "yes" exist or string "no" exist. So it is allways true.
If you want to check if string contains some value you can do it either by regular expression (more) or simply by indexOf eg:
var id;
id = prompt("Are you happy?");
if (id == "yes") {
alert("That's cool.");
} else if(id == "no") {
alert("I'll make you happy.");
} else if(id.indexOf('yes') >= 0 || id.indexOf('no') >= 0) {
alert("Type only yes or no, without any extra texts.");
} else {
alert("you didn't even answer the question.");
}
Regards, KJ

Validate that multiple Prompts have a value

I´m trying to write a simple test where I ask for name and age in separate Prompts. I´d like to validate user really adds a value in both prompts.
What´s the best way to do this validation without duplicating code?
When I click "OK" with no value, it does not ask me to add a value
function showInfo() {
//Asking for name in a prompt
var name = prompt("Name: ","");
//Checking if it is null or empty
if (name == null || ""){alert("Please enter your name");}
//Same for age
var age = prompt("Age: ","");
if (age == null || ""){alert("Please enter your age.");}
}
Also, noticed that "null" is to check the "Cancel" button, but I was able to test that if you click "Cancel", and click "Cancel" again, it does not ask for a value. How can I solve this issue?
You if condition is wrong. You should use
if (name === null || name === "") {
//you code here
}
And If you like to show prompt continusly unless user enters input below code will work:
function showInfo() {
while(1) {
//Asking for name in a prompt
var name = prompt("Name: ","");
if (name === null || name === ""){alert("Please enter your name");}
else break;
}
console.log("Name= "+name);
while(1) {
//Same for age
var age = prompt("Age: ","");
//Checking if it is null or empty
if (age === null || age === ""){alert("Please enter your age.");}
else break;
}
console.log("Age ="+age);
}
showInfo();
You could put it in a loop to ask again. Here I'm using !name to check for the
"truthyness" of name. null and an empty string are both "falsy" so, !name
will return true for them, a non-empty string is truthy, so !name will
return false for them.
function ask (msg, errMsg) {
var name;
do {
name = prompt(msg);
//Checking if it is null or empty
if (!name) {
alert(errMsg);
}
} while (!name);
return name;
}
function showInfo() {
var name,
age;
name = ask("Name:", "Please enter your name");
age = ask("Age:", "Please enter your age.");
}
showInfo();
That said, unless this is just a prototype or a small personal project only you
will use, don't do it this way! Sticking the user in a loop prompt will
frustrate most people. Most modern browsers include a "Don't show me this again"
check box. I'm not sure what would happen if the user checks it, the browser
might continue in an infinite loop and lock up or crash.
Instead it would be better to do it with a form on the page:
var elShowInfo = document.getElementById('show-info'),
elName = document.getElementById('name'),
elAge = document.getElementById('age'),
elOut = document.getElementById('output');
function showInfo (ev) {
// stop the form from submitting
ev.preventDefault();
var name = elName.value,
age = elAge.value;
if (name && age) {
// do something with name/age
elOut.textContent = name + ' is ' + age + ' years old.';
}
}
elShowInfo.addEventListener('click', showInfo, false);
<form>
<label for="name">Name:</label> <input id="name" placeholder="Please enter your name">
<label for="age">Age:</label> <input id="age" placeholder="Please enter your age">
<button id="show-info">Show info</button>
</form>
<div id="output"></div>
Every time the Show Info button is pressed it checks for the data once and then does something with it if it is there; otherwise it does nothing.
One thing to note, both prompt and the .value property of an element return strings so if you are going to use age to do some sort of calculation you will need to convert it to a number either using parseInt, age = parseInt(age, 10) or an unary +, age = +age;.
Further reading:
Truthy and Falsy: When All is Not Equal in JavaScript
Introduction to the DOM
#Arshad answer adds more clarity.
on a side note, the reason why the || didn't work is the order of evaluation.
if (age == null || "") --> evaluated as
if ((age == null) || "") --> true on Cancel, false on Ok
Hope this helps !

JavaScript logical operators questions?

I just don't understand how && and || work. I wrote up a small code to help myself out and it just doesn't make any sense to me. You would click a button and the startGame() would be called.
var startGame = function() {
var quizAnswers = {
name: prompt("What is your name?").toUpperCase(),
age: prompt("What is your age?"),
snack: prompt("What is your favorite type of snack out of the following: ice cream, apple, chips, cookies?").toUpperCase()
};
quizAnswers.confirmAge = function () {
while (isNaN(this.age) === true) {
this.age = prompt("The age that you entered- " + this.age + " -is not a number. Please enter a number.");
};
};
quizAnswers.confirmAge();
quizAnswers.confirmSnack = function () {
while ((this.snack !== "ICE CREAM") && (this.snack !== "APPLE") && (this.snack !== "CHIPS") && (this.snack !== "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is unrecognized. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
};
quizAnswers.confirmSnack();
It would get name, age, and favorite snack and then check to see if the age is a number and the snack entered is one of the listed options. After messing with the while loop in the confirmSnack function, I figured out how to make it work, which is displayed above. But why is it && and not ||. And is there a way to shorten it like:
while (this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is invalid. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
So the questions are to explain why &&(and) is used instead of ||(or) and if there is a way to shorten this code so i don't have to enter "this.snack !==" four times. I'm not an expert so please try to keep it simple.
The && operator is working just fine. This is actually a question of logic, not javascript.
You are asking the question while the answer is different from ALL of the possible answers.
It could be rewritten with || as the follwing:
while (!(this.snack == "ICE CREAM" || this.snack == "APPLE" || this.snack == "CHIPS" || this.snack == "COOKIES"))
Notice the ! operator in the beginning.
A shorter form to write it would be:
answers = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (answers.indexOf(this.snack) < 0) { ... }
Here you define a list of possible answers and you want to accept, and check if the answer is among them.
The && and || operators compare boolean values. (Boolean means true/false). That means if you execute 5 == 5 && 6 + 1 == 7 the interpreter does the following things:
Evaluate 5 == 5. The == operator returns true if both sides are equal (as you probably know). Since 5 == 5 is true, we look at the next value (if it were false, because of short circuit operators, it would return false immediately).
Evaluate 6 + 1 == 7. This is also true, so the returned value is true.
The && operator does not compare regular values such as "ICE CREAM" (well it does, but it converts it into a boolean value).
Now let's look at the code you provided:
this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")
First, the javascript interpreter executes ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES"). Since all of those values are true, the value of that expression is true. So this comparison is essentially checking this.snack !== true, which is not what you want.
To solve your problem, I would suggest using indexOf. This checks if an element is in an array and returns -1 if there is no element. For example:
var validSnacks = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (validSnacks.indexOf(this.snack) === -1) {
// Do something
}
If you use or(||), if any of the sub-statements (e.g. this.snack !== "ICE CREAM") evaluate to true, the entire statement will be true, causing the prompt to be shown.
On the other hand, using and(&&), all of the sub-statements must be true for the entire statement to evaluate as true, which is the behaviour that you want - you only want the prompt to show if snack is not one of the 4 options.
There is no way to shorten the code in the way you suggest. One thing you could do would be to make an array with the 4 options in it and check if that array contains snack.

Categories

Resources