Null check is creating problems - javascript

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");
}

Related

Why won't my alerts work after my if statements?

I've been trying to get my alerts to pop up after the user enters they enter their Lecture Code but i can't figure out what's going on.
thank you for your time btw!
let employeenum, firstname, surname, hours, employeecode, lecturecode
employeenum = parseInt(prompt("Please enter your Employeer Number"));
firstname = prompt("Please enter your first name");
surname = prompt("Please enter your surname");
hours = parseInt(prompt("Please enter the amount of hours worked"));
employeecode = prompt("Please enter your employee code");
if (employeecode == "L" || employeecode == "l") {
lecturecode = parseInt(prompt("Please enter your Lecturer Qualification Code"))
if (lecturecode == "M" || lecturecode == "m"){
alert("Your Pay per Hour is $575 with a teaching allowance of $2500 per month");
}
else if (lecturecode == "B" || lecturecode == "b"){
alert("Your Pay per Hour is $325 with a teaching allowance of $1250 per month");
}
}
You have a parseInt on lecturecode but are using an if statement looking for a letter.
lecturecode = prompt("Please enter your Lecturer Qualification Code")//you had parseint here

While loop - 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);
}

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.

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.

How can I continue a JavaScript if.. else if statement until I receive valid input?

How can I continue prompting a user for a valid response using if... else if statements? My script currently works once, but then breaks:
var enterNum = prompt("Please enter a number between 1 and 100", "");
if (isNaN(enterNum)){
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
else if (enterNum < 1 || enterNum >100){
enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
}
else{
document.write("Your number is ", enterNum)
}
Thanks in advance!
var enterNum = prompt("Please enter a number between 1 and 100", "");
while(isNaN(enterNum) || enterNum < 1 || enterNum >100) {
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
document.write("Your number is ", enterNum)
var valid = false;
var msg = "Please enter a number between 1 and 100";
while(!valid){
var enterNum = prompt(msg, "");
if (isNaN(enterNum)){
msg = "You did not enter a valid number. Please try again";
}
else if (enterNum < 1 || enterNum >100){
msg = "Your number is not between 1 and 100. Please try again";
}
else{
valid = true;
document.write("Your number is ", enterNum)
}
}
There are a bunch of other ways to do a similar thing, somewhat depending on style. This went for readability. Could also eliminate the valid variable and simply have while(true) then break once the input is correct. The document.write could also be after the while.
You can't with only if/else. Use a loop. Example:
var enterNum = prompt("Please enter a number between 1 and 100", "");
while(true)
{
if (isNaN(enterNum)){
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
else if (enterNum < 1 || enterNum >100){
enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
}
else
break;
}
document.write("Your number is ", enterNum)
use a while loop instead
http://help.dottoro.com/ljqepqhd.php#dowhile
or
http://help.dottoro.com/ljqepqhd.php#while
I hate javascript so my syntax is probably off but something like:
var isValid = false;
var message = "Please enter a number between 1 and 100";
while(isValid == false)
{
var enterNum = prompt(message, "");
if (isNaN(enterNum)){
isValid = false;
message = "You did not enter a valid number. Please try again";
}
else if (enterNum < 1 || enterNum >100){
isValid = false;
message = "Your number is not between 1 and 100. Please try again";
}
else{
isValid = true;
document.write("Your number is ", enterNum)
}
}
Using a do/while loop might be a little neater.

Categories

Resources