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

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

Related

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

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

If String starts with a number check the length of the string

i want to use javascript in a .pdf file.
I want to check if a string starts with "1" or with a letter.
If the string starts with "1" i want to check the length of the string.
If the string is 18 chars long, then i want to call my own created function.
If the String is shorter than 18 chars i want to display a message.
If the string starts with a letter, i want to check the length of the string.
If the string is 11 chars long, then i want to call my own created function.
If the String is shorter than 11 chars i want to display a message.
But how i can do this?
var string = "Your String";
if(string[0] === '1'){
if(string.length >= 18 )
callYourFunction();
else
alert("Your Message");
}
else if(isNaN(string[0])){
if(string.length >= 11 )
callYourFunction();
else
alert("Your Message");
}
Here, string.length returns the length of the string as integer.
isNaN() checks whether the parameter is not a number. It returns false if the parameter is a number.
You can use something similar to this:
if (typeof variableName == 'string' || variableName instanceof String){
if(variableName[0] == '1'){
if(variableName.length == 18){
//call your method
console.log("It's 18th character long");
} else if(variableName.length == 11){
//call another method
console.log("It's 11th character long");
}
}
}
You can select the first character like so - string[0].
Strings behave like arrays in this way.
You can test the length of a string like so - string.length
var string1 = "1dgfe";
if (string1[0] == 1 && string1.length > 18){
yourfunction();
} else if (string1[0] == 1 && string1.length < 18){
console.log('your message');
}

Validating a data input javascript

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number

Integer validation not working as expected

Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.

HTML textfield whose values cannot be 0 using Javascript

I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")

Categories