0

I am writing this basic control structure for a lesson and I am getting some unexpected behavior.

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

if (answer >= 21) {
  alert('good to go!');
}
else if (answer < 21) {
  alert('sorry not old enough');
}
else if (answer != typeof Number) {
  alert('please enter your age as a number');
}
else if (answer === null) {
  alert('you did not answer!');
}

On the very last conditional, I would expect that if I left the prompt empty, it would execute the last alert. However, it just says 'not old enough'. Is it treating no input into the prompt as 0? How can fix this?

Thanks.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
MadCatm2
  • 951
  • 4
  • 24
  • 41

2 Answers2

0

Prompt doesn't return null if the user hits OK, to test for emptiness, you need to check if the string is empty answer === ""

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
0

You need to move the last two checks to the top since "" < 21 is true:

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

if (answer === '') {
    alert('you did not answer!');
} else if (isNaN(answer)) {
    alert('please enter your age as a number');
} else if (answer >=  21) {
    alert('good to go!');
} else if (answer < 21) {
    alert('sorry not old enough');
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153