Difference between (age==18) and (age===18) in JavaScript? [duplicate] - javascript

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

Related

Code platoon conditional statements problem set

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

why does "Number" make the "else if" work here?

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

=== won't work even if the statement is true

var age =prompt("What is your age?");
if (age === 21) {
console.log("Happy 21st Birthday!");
}
When I write 21 in the prompt, it gives me an undefined, if I replace the === with == then it will work. Why? 21 is the same type and value as the 21 I write in the prompt
Your variable age gets a String from the prompt.
For it to work you need to convert it to an int with the operator +:
If the use of the + operator feels strange to you in this case, you can always use the function parseInt() instead. It will achieve the same result.
var age = +prompt("What is your age?");
// ^ Converts your String to an int
if (age === 21) {
console.log("Happy 21st Birthday!");
}
The prompt() function returns a string. You check for an integer.
Basically == checks if the value of the variable is equal.
=== checks if the value and type is equal.
You can find more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
=== is check the value and type of variable and prompt return string value thats why === return false because prompt return string 21 and you compare with int 21 so return false
so below to way to get your output using == or string to int conversion
var age = prompt("What is your age?");
if (age == 21) {
console.log("Happy 21st Birthday!");
}
//OR
if (parseInt(age) === 21) {
console.log("Happy 21st Birthday!");
}

Checking if variable is an Integer in Javascript

I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.
prompt will always return a string so in your case:
var integerAge = parseInt(age);
if(!isNaN(integerAge) && age === '' + integerAge)
alert("data is integer")
else
alert("data is not an integer")
In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0 or custom minimum and maximum in the next validation step.
Prompts always return strings, but since JS is loosely typed language, those Strings will get autocasted into Numbers when needed (Integers are called Numbers in JS), which is why your example works fine.
For a better check, you can use !isNaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
alert(!isNaN('10'));
alert(!isNaN('abc'));
alert(!isNaN(10));
For the lunatic downvoters, here's an optimized version of OP's code:
var age = parseInt(prompt("Please enter your age", "Enter age"), 10);
alert(isNaN(age) ? 'Not a number' : age);
You can try this one to check if its an integer:
function isInteger(x) {
return x % 1 === 0;
}

Age verification, ensure is not blank and not less than 18

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

Categories