short Javascript program questions( erro output) - javascript

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.

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

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.

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>

Categories

Resources