3
<script>
var p=prompt("how old are you","");
if(p)
alert(p+" is your age");
else
alert("You dint entered any input or you have entered a non-integervalue");
</script>

This is my javascript code. Suppose i enter my age 0.
Then p=0 this implies the else part of the code will execute. But the code is executing the if part!
Why is it happening?
I'm new to Web-development , Please Help.
Thank You!

  • Possible duplicate of [In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?](https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals) – FuzzyTree Oct 22 '17 at 05:43
  • Because it returns a string of zero `"0"` not a number of `0`. only empty strings `""` get coerced into `false` – Jay Harris Oct 22 '17 at 05:44
  • That's because your if condition is checking for any input. It doesn't know you are expecting a number or the amount. Check this [**JsFiddle Demo**](https://jsfiddle.net/3rpmsoxh/) – NewToJS Oct 22 '17 at 05:44

3 Answers3

1

Just write this code :

var p=prompt("how old are you","");
alert(typeof(p));

You will see that it is a string. "0" is a string, so it will be evaluated to true as it is not empty or null.

So, parse it to a number before doing anything.

Miraj50
  • 4,257
  • 1
  • 21
  • 34
1

parseInt() the result of the prompt, that means, parsing the string result to an integer

Now, if the input is "0", it is parsed to 0, and 0 == false.

Thus the "else" condition would take place, as required.

Also, if a non-integer string is entered, such as alphabets, the result would be a NaN and the else part would occur

var p=parseInt(prompt("how old are you",""));
if(p) {
alert(p+" is your age");
}
else {
alert("You dint entered any input or you have entered a non-integervalue");
}
Manav
  • 1,357
  • 10
  • 17
1

If you want to ensure the prompt input is number, you should use isNaN function to check the input.

    var p=prompt("how old are you",""); 
    if(!isNaN(p)) alert(p+" is your age"); 
    else alert("You dint entered any input or you have entered a non-integervalue"); 
Calvin
  • 149
  • 4