I have a task to play a little with if/else if.
i don't understand why, when I write my code like the example below, the "else if(age === 18)" part doesn't work. it shows up as "undefined". the other 2 work.
But, when i add (Number(age) at all of them, it works. Why is that? why can i use 2/3 without "Number", but i need it to use 3/3?
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
You need to convert the string to a number. The easiest way is to take an unary plus +.
With a number, you can check with a strict comparison Identity/strict equality operator === against a number, because you have at least the same type.
var age = +prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else {
alert("Powering On. Enjoy the ride!");
}
prompt returns a string, which cannot be strictly equal to the number 18 since the types are different. It would work, however, if you used loose equality (==).
The simplest way to convert it to a number would be to use the unary plus operator, which has much the same function as the Number function.
var age = +prompt("Please type your age!");
It is because prompt returns a string.
The operators < and > will allow you to compare a string to a number, by pre-converting the string to a number and then comparing them. Read this article for more info on this, called "Type Coersion" in JS.
The === operator however will not do this type coercion/conversion, it will directly compare "18" with 18 and return false.
To fix this, you can instead use the other equals operator, ==, which does include type coercion.
However, a better way of doing it would be to check the input is definitely a number, like this:
var age = Number(prompt("Please type your age!"));
if (Number.isNaN(age)) {
alert("Try again with a number");
} else if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
cause prompt returns a stirng.
But < & > operators converts string to a number
var age = prompt("Please type your age!");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === '18') {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else if (age > 18) {
alert("Powering On. Enjoy the ride!");
}
Related
This question already has answers here:
Console.log comparison with number
(3 answers)
Javascript === (triple equals)
(8 answers)
Closed last year.
I was doing this program and not getting output but if I entered age 18 after typecasting the age in the second block of code I got the output why is it so?
And if I use only two "==" sign then also I got the output but in case of "===" I didn't get the output.
age == 18 Got the output
Number(age)===18 Got the output
age === 18 Didn't got the output
Both the codes are given below.
With "==="
var age=prompt("Enter your age");
if(age<18){
alert("Sorry, You are too young to drive this car Powering off");
}else if(age>18){
alert("Powering On Enjoy the ride!");
}else if(age===18){
alert("Congratulation on your first riding Enjoy the ride!");
}
With typecasting "Number(age)===18"
var age = prompt("What is your age?");
if (Number(age) < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (Number(age) > 18) {
alert("Powering On. Enjoy the ride!");
} else if (Number(age) === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
}
prompt always returns a value in string format.
Suppose a string and number have same value (say 18 and '18'). Here the value is same, only the type differs. Comparing a string value with a number will return true if only value is compared and false if type is also compared.
== compares two value without comparing the types. == is called as Abstract Equality Comparison which compares value only, not type. == will perform a type conversion when comparing two things.
console.log(18 == '18'); // Expect true
=== compares two value by comparing the types. === is called as Strict Equality Comparison this will compare both value and type
console.log(18 === '18'); // Expect false
In case of Number(age) === 18, the string age is converted to numeric age and hence this both the value is od type number. Hence this will return true
Read More on == and ===
const age = prompt("Enter your age");
console.log(`Type of Age = ${typeof age}`);
const numbericAge = +age; // String to number conversion, Same as Number(age)
console.log(`Type of Numeric Age = ${typeof numbericAge}`);
if (numbericAge < 18) {
alert("Sorry, You are too young to drive this car Powering off");
} else if (numbericAge > 18) {
alert("Powering On Enjoy the ride!");
} else if (numbericAge === 18) {
alert("Congratulation on your first riding Enjoy the ride!");
}
Getting my coding learning path started and I've run across a hiccup. I'm trying to write a program that represents the below;
// Write a program that prints a message to the screen based on a users age and country.
// Feel free to change these variables or create new ones so you can test all cases.
const age = 20
const country = 'USA'
// if the user is younger than 16 print "You're not old enough to do anything yet."
// if the user is at least 16 but not yet 18 print "Be careful driving."
// if the user is 18 but not yet 21 and the user lives in the USA pring "Go Vote!"
// if the user is at least 18 but younger than 21 and lives outside of the US print "You can probably have some wine."
// In all other cases print "You're old enough to figure it out for yourself."
So far ive got this:
const age = 20
const country = "USA"
const otherCountry = "Other country"
console.log(age)
console.log(otherCountry)
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
else if (age >=16 && age <=18) {
console.log ("Be careful driving")
}
else if (age >=18 && age <=21 && country) {
console.log("Go Vote!")
}
else if (age >=18 && age <=21 && otherCountry){
console.log ("You can prbably have some wine")
}
else
{console.log ("You're old enough to figure it out")
}
I cant seem to figure out how to get the country to be expressed in the "else if" statement. Noobies got to start somewhere. Thanks in advance
You have a problem with your logic.
First of all not yet 18 probably means < 18 and not <= 18. (same for 21)
Second, once you are in your "Go vote" branch, you can never enter the "Wine" branch anymore, because once, one condition is hit in an if .. else if .. else no other conditions will be evaluated any more.
So, if you have a person between 18 and 21, you have to check the addtional condition (ie lives in USA or any other country) in that branch.
let age = 19;
let livesin = "USA";
if (age < 16 ) {
console.log("You're not old enough to do anything.")
}
//you don't need >=16 here, because as the first condition failed
//we alread know that age >= 16
else if (age < 18) {
console.log ("Be careful driving")
}
//you don't need >=18 here, because as the first and second condition failed
//we already know that age >= 18
else if (age <21) {
//for people between 18 and 21, check if they live in the USA or not
if (livesin === "USA") console.log("go vote");
else console.log("You can prbably have some wine")
}
else {
console.log ("You're old enough to figure it out")
}
I am trying to write a code to answer the following. I have options of prizes. To be eligible for the prizes, you need to be within the age range of 20 and 40. If you are not eligible an alert saying you are not eligible will appear. If you are eligible; prompt will ask you for which prize you want and you need to answer with a numeric value. After they answer they will receive an alert that says "You will receive (prize, collected from the array) in your post within 2 weeks."
I have gotten this far with my code:
var prize = [
"0 = iPhone",
"1 = iPad",
"2 = iMac",
"3 = iPod"
];
var age = prompt("Please enter your age");
if (20 >= age && age <= 40){
alert("Sorry, you are not eligible for a prize.");
} else {
prompt("Which prize would you like to receive?");
} else if {
Would someone want to give me a hand? Thanks :)
You have mixed up a lot of the logic there, and actually put the "success" code within the "failure" condition.
I have no idea what you intend to do with the second prompt to choose the prize - and have even less clue why someone's age is the limiting factor in being eligible for a prize - but here is some logic that will correctly filter your desired age range:
var age = prompt("Please enter your age");
if (age >= 20 && age <= 40){
// handle successful prize claim here
}
else {
alert("Sorry, you are not eligible for a prize.");
}
it is supposed to make sure that the first 2 elem[0] and elem[1] are not blank and if they are to return and error or display the name
the second part is to give an error if the age, elem[2] is less than 18
function checkForm()
{
var elem = document.getElementById('myForm').elements;
if(elem[0].value or elem[1].value ==(""))
{
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
if number(elem[2].value) < 18
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}
looks like you aren't formatting your if() statements correctly.
instead of 'or', you should use || (two pipe symbols).
Also, correct format for the statement:
if(condition){
what to do if 'condition' is true
}
so, correct format:
if(elem[0].value =="" || elem[1].value ==""){
alert("Please enter your first and last name");
}
alert("Your name is " + elem[0].value + "" + elem[1].value);
use this formatting for your other code as well.
Your first conditional
if(elem[0].value or elem[1].value ==(""))
This error in this line stems from a colloquialism in English: when you say "the cat or the dog is here", this is a shortcut for the proper English, which is "the cat is here, or the dog is here".
Programming languages usually don't have colloquialisms; your code evaluates elem[0].value, then performs a boolean "or" operation on it with the expression elem[1].value == ("") as the other comparator.
That is, your line is equivalent to:
if ((elem[0].value) or (elem[1].value == ""))
and I think it's clear that this was unintended.
You probably meant to write:
if (elem[0].value == "" || elem[1].value == "")
Note that I've also replaced the non-existent or with ||, which means "or".
Your second conditional
In this line:
if number(elem[2].value) < 18
You forgot the surrounding ().
So:
if (number(elem[2].value) < 18)
Though it's not clear what you meant by number. Further study the text that instructed you to write that.
Other notes
Your indentation is generally messy.
I hope you are enjoying learning JavaScript. Keep reading your book and studying the syntax, because you generally have to get it precisely right: details matter!
try:
if (!isNaN(number(elem[2].value)) // its a number?
{
if (number(elem[2].value) < 18) // add ()
{
alert("You are to young to be playing on this computer.");
}
alert("Your age is "+ elem[2].value);
}
I'm learning JavaScript using the Code Academy website and whenever I try an if / else program it always comes up with expected a identifier. I don't know what I'm doing wrong. My program looks like this:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log{"You are allowed to play but I take no responsibily";
}
else
{
console.log ;"Have fun playing"
}
To call the console.log function, you will need (round) parenthesis around its argument(s). Also you were missing the opening brace after the if-condition:
confirm("Are you ready?")
var age = prompt("What's your age?");
if (age <= 18) {
console.log( "You are allowed to play but I take no responsibily" );
} else {
console.log( "Have fun playing" );
}
Btw, you can omit the braces if there is only a single statement in the body of an if, else, for, etc. However, it's important to use proper indentation then:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log( "You are allowed to play but I take no responsibily" );
else
console.log( "Have fun playing" );
Also notice that prompt() is returning a string, which you might want to parse into a number before comparing it against 18:
var age = parseInt( prompt("What's your age?"), 10);
if(confirm("Are you ready?"))
{
var age = prompt("What's your age?");
if (age <= 18)
{
console.log("You are allowed to play but I take no responsibily");
}
else
{
console.log("Have fun playing");
}
}
You need to use proper syntax. console.log for example is console.log("text")
Be sure to have a semi colon after each statement
confirm("Are you ready?")
var age = prompt("What's your age?")
needs to read
confirm("Are you ready?");
var age = prompt("What's your age?");