While loop - JavaScript - javascript

let age = "";
while (age !== NaN) {
age = prompt("what is your age");
Number(age);
}
I can not leave the while loop although I write a number in the prompt box, why?

You can use isNaN() function to determine whether a value is NaN or not. You have to add age == "" as part of the condition with || to pass for the initial value (empty string).
The condition should be:
while (isNaN(age) || age == "")
You also have to re-assign the converted value to the variable.
let age = "";
while (isNaN(age) || age === "") {
age = prompt("what is your age");
if(age == null)
break;
else
age = Number(age);
}

Related

Null check is creating problems

let age = prompt('What is your name?');
if(age != null){
document.write(`Your name is ${age}`)
}else{
document.write("You didn't enter your age");
}
Null check isn't working like even when I am leaving it blank it is showing : Your name is
but when i wrote this -
let age = prompt('What is your name?');
if(age == null){
document.write(`Your name is ${age}`)
}else{
document.write("You didn't enter your age");
}
It is always showing 'You didn't enter your age'
Because when you don't enter something, age does not contain null but an empty string (a string of length 0). You can confirm this by:
let age = prompt('What is your name?');
console.log(age); // prints ''
console.log(age.length); // prints 0
if(age != null){
document.write(`Your name is ${age}`)
}else{
document.write("You didn't enter your age");
}
In reality, you just need to do:
let age = prompt('What is your name?');
if(age){
document.write(`Your name is ${age}`)
}else{
document.write("You didn't enter your age");
}

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 statement that makes a user enter a value

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.

Text character limit

I have this script and want to implement 12 character limit for each name like first name, last name and middle name can not have more than 12 characters each.
var name = prompt("Please enter (Last name, First name, Middle initial)");
function fullName(alf) {
var validate = alf.match(/^[a-zA-Z', ]+$/);
if (validate == name)
return true;
else
return false;
}
var tst = fullName(name);
if (tst)
document.write("Valid Name");
else
document.write("Invalid Name");
It's fairly simple. Just check the prompt input length as in this snippet. (However if you use input field instead of a prompt you can limit its length by defining "maxlength" e.g. <input type="text" name="yourname" maxlength="10">)
var name = prompt("Please enter (Last name, First name, Middle initial)");
function fullName(alf) {
var validate = alf.match(/^[a-zA-Z', ]+$/);
if (validate == name)
return true;
else
return false;
}
var len = name.length;
var tst = fullName(name);
if (tst && len <= 39) // len 12 * 3 for each value + 3 for spaces/commas separating names.
document.write("Valid Name");
else
document.write("Invalid Name");

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