JavaScript if/else statement that makes a user enter a value - javascript

How would you make an if/else statement loop back to the beginning to get user information?
This is the code I got so far:
var age = prompt("Please enter your age");
if(age == 21 ) {
alert("Happy 21st Birthday!");
} else if (age > 21 ) {
alert("You are old");
} else {
alert("Please enter an age");
}
I'm trying to make it go back to the beginning to make the user enter information.

var age = '';
while(age == '' || age == 'ok'){
age = prompt("Please enter your age");
if($.isNumeric(age) === false){
continue;
}
if(age == 21 ){
alert("Happy 21st Birthday!");
continue;
}
if (age > 21 ){
alert("You are old");
continue;
}
if (age < 21){
alert("You are too young to be in this bar!");
}
}

for (let age = prompt('Please enter your age'); ;) {
if (age == 21) {
alert('Happy 21st Birthday!');
break;
} else if (age > 21) {
alert('You are old');
break;
} else {
age = prompt('Please enter your age');
}
}

You separate validation logic from the user input logic.
If this is console app then you would place a loop around the prompt and then validate the user age, if the age is valid break out of the loop otherwise let the loop continue.
On a web page you would wrap it in a function and based on the result manipulate the view based on if the age is correct or not. So you would perhaps show an error message if the age is invalid or go to the next page if the age is valid.
You should wrap the if statements which make up the validation logic in into a function perhaps validateAge that returns true or false, that way no matter what you implement you can use the same method.

Working off of #wallyk's suggestion using a while loop yields this example:
var age = false;
while (!age) {
age = prompt("Please enter your age");
if (age == 21) {
alert("Happy 21st Birthday!");
} else if (age > 21) {
alert("You are old");
} else if (!!age && age < 21) {
alert("You are young");
} else {
alert("Please enter an age");
age = false;
}
}
It will keep looping until you type a valid number answer. I also added in a check to see if the user input an age under 21, since I'm guessing you don't want to keep looping forever if the user is under 21 (or keep looping until they turn 21) but that part can easily be removed if you want.

Related

I want to end the while loop when user clicks cancel in the confirm box

let age = Number(prompt('Enter your age'))
if (age <= 0) {
alert('Enter a valid age')
console.error('Enter a valid age');
}
if (age < 18) {
alert('You cannot drive')
}
else if (age >= 18) {
alert('Yes you can drive')
}
let askAgain = confirm('Do you want to see thr prompt again?')
while (askAgain == true) {
let age = Number(prompt('Enter your age'))
if (age <= 0) {
alert('Enter a valid age')
console.error('Enter a valid age');
}
else if (age >= 18) {
alert('Yes you can drive')
}
if (age < 18) {
alert('You cannot drive')
}
let askAgain = confirm('Do you want to see thr prompt again?')
}
I want to make the confirm box go away if the user selects cancel. It works fine the first time but if I select ok first and the while loop executes and then It keeps on showing the confirm box even if I select cancel.
You have declared askAgain variable twice - first outside the while loop and then again inside the loop.
Just remove the 'let' keyword present in front of askAgain (which is present inside of while loop). This will fix the issue.

How to prevent else-statement from being triggered everytime

I'm pretty new into coding and I'm sorry to waste your time with that beginners question. I'm trying to learn JS with a eBook and my exercise atm is to write a programm which saves the entered name (first and lastname) and the entered gender. The programm should check the length of the names and give out an error if the names are too long or too short. In addition the book forces me to only accept m or f when the gender is asked.
If everything is entered corretly it should give out something like:
"Allright. Welcome in our society, fName lName!
Ah, we really want other (fe)males like you!"
Only if you entered something different than m/M/f/F for your gender the else-statement should be triggered and you should read "Sorry, we do not support gender-diversity here" (its a joke oc) But the else-statement gets always triggered. I have the same problem in different exercises so I hope I can learn from this.
let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');
if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
console.log('Sorry. One of your names is too short/long')
}
if (gender === 'm' || gender === 'M') {
console.log('Ah, we really want other males like you!');
} else {
console.log('Sorry, we do not support gender-diversity here');
}
if (gender === 'f' || gender === 'F') {
console.log('Ah, we really want other females like you!');
} else {
console.log('Sorry, we do not support gender-diversity here');
}
You currently have:
if (a) {
// Output 1
} else {
// Output 2
}
if (b) {
// Output 3
} else {
// Output 4
}
There's no connection between condition a and condition b, and you don't want Output 2 to occur just because a was false.
Instead, use else if:
let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');
if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
console.log('Sorry. One of your names is too short/long')
}
if (gender === 'm' || gender === 'M') {
console.log('Ah, we really want other males like you!');
} else if (gender === 'f' || gender === 'F') {
console.log('Ah, we really want other females like you!');
} else {
console.log('Sorry, we do not support gender-diversity here');
}
Or you might consider switch:
let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');
if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
console.log('Sorry. One of your names is too short/long')
}
switch (gender) {
case 'm':
case 'M':
console.log('Ah, we really want other males like you!');
break;
case 'f':
case 'F':
console.log('Ah, we really want other females like you!');
break;
default:
console.log('Sorry, we do not support gender-diversity here');
break;
}
(I do strongly recommend not limiting to binary gender choices in 2019, but I assume that's a bit tangential to your question.)
if (gender === 'm' || gender === 'M') {
console.log('Ah, we really want other males like you!');
} else if (gender === 'f' || gender === 'F') {
console.log('Ah, we really want other females like you!');
} else {
console.log('Sorry, we do not support gender-diversity here');
}
should do it
Do with else if statement while validate gender.And your option of gender was m or w but you are validate f instead of w
Then first and last name both are min length above 6 and you are using && its only true both first and last match.
If you need both first and last sperate validate use with ||.
Like this
(firstName.length >= 6 && firstName.length <= 16) || (lastName.length >= 3 && lastName.length <= 12)
Snippet
let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)');
if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
console.log(`Allright. Welcome in our society, ${firstName} ${lastName}!`);
} else {
console.log('Sorry. One of your names is too short/long')
}
if (gender === 'm' || gender === 'M') {
console.log('Ah, we really want other males like you!');
}else if(gender === 'w' || gender === 'W') {
console.log('Ah, we really want other females like you!');
} else {
console.log('Sorry, we do not support gender-diversity here');
}
welcome to JavaScript :D
You don't have a problem with the code but with the logic.
I'll make it simple since you stated that you are new to coding:
You have two if clauses. Both will run.
If I select that I am a male person the else-if of the female check
will run because I haven't entered f/F.
If I select that I am a female person the else-if of the male person
will run because I haven't entered m/M.
=> Easiest solution: remove the else parts and add a check at the end like: "If person hasn't entered m or M or f or F => console.log(..)"
PS: This is not the best solution but it's easier to understand for people who are new to coding.
You can improve your code by following steps
Use toLowerCase() on gender so you need to check for only one letter.
First you need to check if gender is f or m and then inside that if block you should log the message. and else block should log message Sorry, we do not.....
Create a Boolean which will keep track if the first test i.e length of names is passed or not. If its not passed you should go to the gender checks
let firstName = prompt('Whats your first name?');
let lastName = prompt('What is your last name?');
let gender = prompt('Please type in your gender (m or w)').toLowerCase();
let check = true;
if (firstName.length >= 6 && firstName.length <= 16 && lastName.length >= 3 && lastName.length <= 12) {
check = false;
} else {
console.log('Sorry. One of your names is too short/long')
}
if(['m','f'].some(x => x === gender) && !check){
let str = (gender === 'm') ? 'males' : 'females';
console.log(`As, we really want other ${str} like you`);
}
else {
check || console.log('Sorry, we do not support gender-diversity here');
}

Javascript if else beginner

Could someone give me a hint what is wrong here?
var age = 18;
prompt('please add your age...');
if (age > 18) {
alert("Welcome.");
}
if (age < 18) {
alert("You are not allowed..");
}
You aren't assigning the input to the age variable, but you are setting it to 18, which is not covered by your if or else. Few things you need to do:
Please assign the variable to the user given value.
Check for equality too. What if the user gives 18?
Also, using else if would be a better candidate here.
Your final code should be:
// Change below.
var age = prompt('please add your age...');
// Change condition below.
if (age >= 18) {
alert("Welcome.");
} else if (age < 18) { // Use else if.
alert("You are not allowed..");
}
// var age = 18
// prompt('please add your age...') // this prompts but isnt doing anything with the returned value. try
var age = prompt('please add your age...')
if (age > 18) {
alert('Welcome.')
}
if (age < 18) {
alert('You are not allowed..')
}
if (age === 18) {
alert('this is true')
}
Neither of your conditions were true. Age WAS 18, but you were checking if age was above of below 18.
Also if you wanted to assign the user input value to age, the prompt function returns that value into the age variable like above.
Use a variable for your prompt input.
const age = 18;
const value = prompt('please add your age...');
if (age > value) {
alert("Welcome.");
}
else if (age < value) {
alert("You are not allowed..");
}
const age=prompt('please add your age...');
if (age > 18) alert("Welcome.");
else alert("You are not allowed.");

setting parameter typeof for a function in javascript

i would like my code to return 'invalid age' if the parameter given in the function is not a number,instead am getting a system referenceError.any one who can help out?
function canIWatch(age){
this.age = age
if ( age >=1 && age <= 6 ) {
return "You are not allowed to watch Deadpool after 6.00pm.";
}
else if (age >= 7 && age <= 17){
return "You must be accompanied by a guardian who is 21 or older.";
}
else if (age >= 18 && age <= 24){
return "You are allowed to watch Deadpool, right after you show some ID.";
}
else if (age >= 25 ){
return "Yay! You can watch Deadpool with no strings attached!";
}
else if (typeof age !== 'number'){
return "Invalid age.";
}
}
the code below is to pass the tests below.
edited code;
function canIWatch(age){
this.age = age
if (typeof age !== 'number' || age <=0){
return "Invalid age.";
}
else if ( age >=1 && age <= 6 ) {
return "You are not allowed to watch Deadpool after 6.00pm.";
}
else if (age >= 7 && age <= 17){
return "You must be accompanied by a guardian who is 21 or older.";
}
else if (age >= 18 && age <= 24){
return "You are allowed to watch Deadpool, right after you show some ID.";
}
else if (age >= 25 ){
return "Yay! You can watch Deadpool with no strings attached!";
}
}
test codes for the function;
describe('canIWatch tests', function () {
it('Should return the appropriate message for age less than 6', function () {
expect(canIWatch(5)).toEqual('You are not allowed to watch Deadpool after 6.00pm.');});
it('Should return the appropriate message for age less than 17', function () {
expect(canIWatch(15)).toEqual('You must be accompanied by a guardian who is 21 or older.'); });
it('Should return the appropriate message for age less than 25', function () {
expect(canIWatch(20)).toEqual('You are allowed to watch Deadpool, right after you show some ID.'); });
it('Should return the appropriate message for age above 25 than 6', function () {
expect(canIWatch(30)).toEqual('Yay! You can watch Deadpool with no strings attached!');});
it('should return an appropriate message if provided age is invalid', function () {
expect(canIWatch(-1)).toEqual('Invalid age.');});});
the question is;
Deadpool is an R-rated movie.
Write a JavaScript function named canIWatch that will take age as a parameter.
If the age is less than 6, return You are not allowed to watch Deadpool after 6.00pm.
If the age is 6 or more but less than 17, return You must be accompanied by a guardian who is 21 or older.
If the age is 17 or more but less than 25, return You are allowed to watch Deadpool, right after you show some ID.
If the age is 25 or greater, return Yay! You can watch Deadpool with no strings attached!.
If the age is invalid, return Invalid age.
Here you go. Your code didn't work because the function automatically parses the string into an integer. Just try by yourself by typing in the console: '123' > 23 or false < 32.
Using mathematical operators will always parse it's components into integers. That's why the validation have to be on the first position.
age = '12';
if (typeof age !== 'number') {
console.log("Invalid age.");
} else if (age >= 1 && age <= 6) {
console.log("You are not allowed to watch Deadpool after 6.00pm.");
} else if (age >= 7 && age <= 17) {
console.log("You must be accompanied by a guardian who is 21 or older.");
} else if (age >= 18 && age <= 24) {
console.log("You are allowed to watch Deadpool, right after you show some ID.");
} else if (age >= 25) {
console.log("Yay! You can watch Deadpool with no strings attached!");
}
If the value passed in isn't a number then it's definitely not going to >= 1 or whatever so there's really no need at the point testing it. If you move your test for your typeof number up the top your function I'm tipping it will probably solve your problem:
function canIWatch(age){
if (typeof age !== 'number') return "Invalid age.";
this.age = age
if ( age >=1 && age <= 6 ) {
return "You are not allowed to watch Deadpool after 6.00pm.";
}
else if (age >= 7 && age <= 17){
return "You must be accompanied by a guardian who is 21 or older.";
}
else if (age >= 18 && age <= 24){
return "You are allowed to watch Deadpool, right after you show some ID.";
}
else if (age >= 25 ){
return "Yay! You can watch Deadpool with no strings attached!";
}
}
function canIWatch(age) {
if (age >= 1 && age <= 6) {
return "You are not allowed to watch Deadpool after 6.00pm.";
} else if (age >= 7 && age <= 17) {
return "You must be accompanied by a guardian who is 21 or older.";
} else if (age >= 18 && age <= 24) {
return "You are allowed to watch Deadpool, right after you show some ID.";
} else if (age >= 25) {
return "Yay! You can watch Deadpool with no strings attached!";
} else if (isNaN(age)) {
return "Invalid age.";
} else if (!age) {
return "Age must be informed.";
}
}
function checkMyAge() {
var age = document.querySelector('#ageInput').value;
alert(canIWatch(age));
}
<input id="ageInput" type="text" />
<button onclick="checkMyAge()">Check</button>

short Javascript program questions( erro output)

const HIGH_AGE = 70, MAX_AGE = 120, BABIE_AGE=4, TEEN_AGE=16;
function main ()
{
var age;
age = Number(prompt('Enter your age:')); //set prompt box ask user's age
if (age < BABIE_AGE || age > MAX_AGE)//if user user's age are below "0" or above "120"
alert('Please Enter Age Within the Range between 0-120!');//output: must enter age in valid age range
else if (isNaN(age) == true || !age)
alert('please enter a valid entry');
else if ((age >= HIGH_AGE) || (age >= 0 && age <= BABIE_AGE))//if age between 0-4 or above 70
alert('You may travel for free');//output: they can travel for free
else if (age >= CHILDREN_AGE && age <= TEEN_AGE )//if user's age are under 16
alert('You may travel with a half price ticket');//output they can travel for half-price
else
alert('You must travel with a full price ticket'); //others all travel with full price
}
Use isNaN function:
if (isNaN(age)) {
// ... age is not valid number
}
Number(prompt('...')) will return NaN value if it can't interpret input as numeric.
Just check if it is a number:
age = prompt('Enter your age:');
if (age == +age) alert("Please insert a number!");
else {
// do what you want
}
I just edited your function. You can try it.
const HIGH_AGE = 70, MAX_AGE = 120, BABIE_AGE=0, CHILDREN_AGE=4, TEEN_AGE=16;
function main () {
var age;
while(/^(?:[1-9]+(?:[0-9]+)?|0)$/.test((age = prompt('Enter your age:'))) == false) {
alert("You must enter number!");
}
age = Number(age);
if (age < BABIE_AGE || age > MAX_AGE)//if user's age are below "0" or above "120"
alert('Please enter age within the range between 0-120!');//output: must enter age in valid age range
else if ((age >= HIGH_AGE) || (age >= BABIE_AGE && age <= CHILDREN_AGE))//if age between 0-4 or above 70
alert('You may travel for free');//output: they can travel for free
else if (age >= CHILDREN_AGE && age <= TEEN_AGE )//if user's age are under 16
alert('You may travel with a half price ticket');//output they can travel for half-price
else
alert('You must travel with a full price ticket'); //others all travel with full price
}
Look at this code:
while(/^(?:[1-9]+(?:[0-9]+)?|0)$/.test((age = prompt('Enter your age:'))) == false) {
alert("You must enter number!");
}
Here is working jsfiddle:
http://jsfiddle.net/zono/varrwx32/14/
A quick and dirty solution (the only one i can think of this quickly), is to use parseInt();
I hope this helps.

Categories

Resources