1

Let's say I have this snippet.

var age = prompt('what is your age?');

if (age === 30)
{
alert('your age is 30');
}

When I entered 30 in the prompt, the if statement doesn't trigger. I suspect it has to do with floating point rounding errors, but don't really know for sure. Would be great to hear your thoughts on this.

stanigator
  • 10,768
  • 34
  • 94
  • 129

1 Answers1

11

window.prompt() returns a string. A string is not identical to a number. Use either of the following:

if (age === '30') 
if (+age === 30)  // Explicit type conversion
if (age == 30)    // Implicit type conversion

For notes on the explicit conversion, see this answer. For example, An input of 00030 may also be valid.

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    OP might also be missing understanding of what === really means - might want to include that as well – JRaymond Apr 25 '12 at 21:54
  • @JRaymond If that's the case, I refer to this Q&A: http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – Rob W Apr 25 '12 at 21:55
  • I think the main issue is I got confused with string and number types. Perhaps I should convert the type in the prompt. – stanigator Apr 25 '12 at 22:04