-11
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

jay may
  • 1
  • 1
  • 7
    Do you know the difference between == and === ? – Andrew Bone Oct 26 '17 at 09:03
  • prompt will get a string and you are comparing number with a string. that's why your condition became false. == checks if the value of the variable is equal. === checks if the value and type are equal. – Harsh Patel Oct 26 '17 at 09:03
  • 5
    Possible duplicate of [Difference between == and === in JavaScript](https://stackoverflow.com/questions/523643/difference-between-and-in-javascript) – Durga Oct 26 '17 at 09:06

3 Answers3

2

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!");
}
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • parseInt() might be better for a beginner rather than using short hand – Andrew Bone Oct 26 '17 at 09:06
  • 2
    I see many people not knowing about the shorthand, even advanced ones. I try to advertise it as much as possible :) – Zenoo Oct 26 '17 at 09:08
  • 1
    @AndrewBone I don't see a problem with it, its an answer at the end of the day and I managed to learn something new today. Thanks Zenoo. – Master Yoda Oct 26 '17 at 09:09
  • Good point. It might be worth editing your answer to have both, your call though – Andrew Bone Oct 26 '17 at 09:09
  • @AndrewBone I agree, was just about to suggest adding both methods and possibly a link to documentation for the shorthand. – Master Yoda Oct 26 '17 at 09:10
  • I edited my answer to fulfill both your requests. I can't seem to find any doc on the shorthand for some reason, though. – Zenoo Oct 26 '17 at 09:14
0

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

zruF
  • 50
  • 8
0

=== 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!");
}
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39