I'm trying to direct users to different content based on their age. I'm trying to direct people older than 35 to .if_one, 24-34 to if_two and 18-24 to if_three.. what do I add to check if they are between 18-24 or 25-34?
Here is what I have so far:
$("#age").blur(function() {
$('.a1, .a2').hide();
var age = parseInt($('#age').val());
if (age > 35)
{
$('.if_one').show();
$('#a1').text(age);
alert($('#a1').val());
}
else
{
$('.if_two').show();
$('#a1').text(age);
}
});
You use an if statement with many clauses, and you can use the fact they will be tested in a specific order to your benefit. If you get the second clause, you can assume the first did not trigger, and therefore must not be true.
if (age > 35) {
// triggers if age is over 35
} else if (age > 24) {
// age is not over 35, so triggers if between 24 and 35
} else if (age > 18) {
// age is not over 24, so triggers if between 18 and 24
} else {
// age is not over 18, so triggers if younger than 18
}
You mean like this?
if (age > 35) {
//...
} else if (age >= 24 && age <= 35) {
//...
} else if (age >= 18 && age <= 23) {
//...
} else {
//age is 17 or less, don't know if you want to do something here...
}
Related
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.");
is it possible to refactor and completely avoid many if else if else statements for better readability. for example :
function canIWatch(age) {
if (age < 6 && age > 0) return "You are not allowed to watch Deadpool after 6:00pm.";
else if (age >=6 && age < 17) return "You must be accompanied by a guardian who is 21 or older.";
else if (age >=17 && age < 25) return "You are allowed to watch Deadpool, right after you show some ID.";
else if (age >= 25 && age < 50 ) return "Yay! You can watch Deadpool with no strings attached!";
else if (age >= 50) return " You are too old to watch deadpool";
else return "Invalid age."
}
how can i write a much cleaner code without having this much if else statements
You could change the check and start with the smallest value and skip the else part, because you return.
function canIWatch(age) {
if (age < 0) {
return "Invalid age."
}
if (age < 6) {
return "You are not allowed to watch Deadpool after 6:00pm.";
}
if (age < 17) {
return "You must be accompanied by a guardian who is 21 or older.";
}
if (age < 25) {
return "You are allowed to watch Deadpool, right after you show some ID.";
}
if (age < 50) {
return "Yay! You can watch Deadpool with no strings attached!";
}
return "You are too old to watch deadpool";
}
console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));
A different solution would be to use an array with objects for the terms
function canIWatch(age) {
var terms = [
{ age: 0, text: "Invalid age." },
{ age: 6, text: "You are not allowed to watch Deadpool after 6:00pm." },
{ age: 17, text: "You must be accompanied by a guardian who is 21 or older." },
{ age: 25, text: "You are allowed to watch Deadpool, right after you show some ID." },
{ age: 50, text: "Yay! You can watch Deadpool with no strings attached!" },
{ age: Infinity, text: "You are too old to watch deadpool" },
],
text;
terms.every(function (a) {
text = a.text;
return a.age <= age;
});
return text;
}
console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));
do the fact that you use return you should at least avoid else if but use if only
function canIWatch(age) {
if (age < 6 && age > 0) return "You are not allowed to watch Deadpool after 6:00pm.";
if (age >=6 && age < 17) return "You must be accompanied by a guardian who is 21 or older.";
if (age >=17 && age < 25) return "You are allowed to watch Deadpool, right after you show some ID.";
if (age >= 25 && age < 50 ) return "Yay! You can watch Deadpool with no strings attached!";
if (age >= 50) return " You are too old to watch deadpool";
return "Invalid age."
}
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>
I wonder if this might come down to personal taste or if there is a generally agreed upon answer to this. I've got a piece of code that could be written in one of two ways and though I think it's something of a trivial example in terms of efficiency, I'd like to know what the generally accepted answer is for future extrapolations.
Here's the code I currently have, essentially a score is passed and some text is updated accordingly. The colour of the text is also changed by the score value.
function getBSTotalText(score) {
var scoreText;
if (score >= 0 && score <= 12) {
scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
scoreText = "16+ NO RISK";
}
else {
scoreText = "";
}
return scoreText;
}
function getBSTotalColour(score) {
var colour;
if (score >= 0 && score <= 12) {
colour = "red";
}
else if (score >= 13 && score <= 14) {
colour = "amber";
}
else if (score >= 15 && score <= 16) {
colour = "yellow";
}
else if (score >= 16) {
colour = "grey";
}
else {
colour = "white";
}
return colour;
}
Now I could easily refactor this into one function and just get it to return an array or object to save basically copying and pasting the same code into a distinct function which from my understanding would conform to DRY but then break SOLID. Would best practice be to keep these functions distinct or merge them into one?
In this example, I'd say there's a compelling reason to refactor to a single function as both functions are concerned with the same thing - getting some formatted text.
function getBSTotalDisplayInfo(score) {
var result = {};
if (score >= 0 && score <= 12) {
result.colour = "red";
result.scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
result.colour = "amber";
result.scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
result.colour = "yellow";
result.scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
result.colour = "grey";
result.scoreText = "16+ NO RISK";
}
else {
result.colour = "white";
result.scoreText = "";
}
return result;
}
Check what part of the code is repeated and move that into an extra function. In your case it's actually quite easy:
function getBSTotal(score) {
// returns some kind of enum
if (score >= 0 && score <= 12)
return 0;
else if (score >= 13 && score <= 14)
return 1;
else if (score >= 15 && score <= 16)
return 2;
else if (score >= 16)
return 4;
else
return 5;
}
function getBSTotalText(score) {
// now map the enum either to a text
return ["0 - 12 HIGH RISK",
"13 - 14 MODERATE RISK",
"15 - 16 LOW RISK",
"16+ NO RISK"
][getBSTotal(score)] || "";
}
function getBSTotalColour(score) {
// … or map it to a color
return ["red",
"amber"
"yellow",
"grey",
"white"
][getBSTotal(score)];
}
You still can make it more efficient by evaluating getBSTotal(score) only once and passing that to the mapping functions instead of score.
I have been trying for a long time and cant seem to figure out what i'm doing wrong. The first too conditions seem to work but the third fails.
function spriteAI1() {
if (c2Sprite.position.x >= 30 && c2Sprite.position.x <= 450) {
c2Sprite.translateX( -10 );
} else if (c2Sprite.position.x <= 30 && c2Sprite.position.x >= -450) {
c2Sprite.translateX( 10 );
} else if (c2Sprite.position.z = 30 && c2Sprite.position.x = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
function spriteAI2() {
if (c2Sprite.position.z >= 30 && c2Sprite.position.z <= 350) {
c2Sprite.translateZ( -10 );
} else if (c2Sprite.position.z <= -30 && c2Sprite.position.z >= -350) {
c2Sprite.translateZ( 10 );
} else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
I'm getting an error on the line
else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30)
the error says invalid left hand in assignment. But the other function has basically the same line and doesn't generate a error.
I can see two problems in your code.
First, comparison is done using == (double equal signs), not a single one (that's assigning a value). That's probably the source of your problem.
In second place, your last two conditions match a common group of values (they are intersected), in the case when c2Sprite.position.x equals 30, it will enter the second "if". It will match the condition for the third one, but it will not run it.
Make sure you always define well-separated groups of conditions (unless that's the behavior that you want).
Just to make it clear:
if (x >= 30) {
/* this matches 30 and above */
}
else if (x == 30) {
/* this won't execute on x == 30, because it entered the first "if" */
}
You should have done this:
if (x > 30) {
/* this matches numbers strictly greater than 30, i.e. 31, 32, 33... */
}
else if (x == 30) {
/* this will match x == 30 */
}
else {
/* any other value for x */
}