mercredi 1 novembre 2017

Boolean returning false for string — needs to be true

In this program, the input of any number below 0 or above 121, or a string should return as 'Invalid Input'. However, when a string is entered, the FULL_PRICE string is returned.

const LOW_AGE = 5,
  HIGH_AGE = 69,
  MID_AGE = 17,
  MAX_AGE = 120,
  FULL_PRICE = "You must pay full price.",
  HALF_PRICE = "You must pay half price.",
  FREE = "You may travel for free";

function main() {
  var age, inputError, cost;

  age = Number(prompt("Enter Your Age:"));

  if (age < 0 || age > MAX_AGE || age == NaN)
    inputError = true;
  else
    inputError = false;

  if (age < LOW_AGE || age > HIGH_AGE)
    cost = FREE;
  else if (age < MID_AGE)
    cost = HALF_PRICE;
  else
    cost = FULL_PRICE;

  if (inputError)
    alert("Input Error.");
  else
    alert(String(cost));
}

As you can see I have tried to trigger a string as false by using age == NaN.

I have also tried to enter age == String.

Surely that would return as true for a string?

Aucun commentaire:

Enregistrer un commentaire