1

I have this problem with the try , catch and throw i errors. But the result am getting is way of mark. this is the code. when i type number greater than 5 into the form field, instead of throwing too high nothing displayed. And when i typed in numbers less than 5, it shows too high, instead of too low. In fact most of the other if conditions does'nt display. except. the empty and too high. can somebody explain which such anomally?

function myFunction() {
  var x, message;

  message = document.getElementById('para');
  message.innerHTML =  '';
  x = document.getElementById('formField').value;

  try {
    if (x == "") throw 'empty';

    if (x == NaN) throw 'not a number';

    x = Number(x);

    if (x < 5) throw 'too low';

    if (x > 5) throw  'too high';

  }
    catch(err){
    message.innerHTML = 'input is ' + err;
  }
}

many of you guys don't seem to understand my problem here this code was a direct copy and paste from W3schools. but its not working normally. the various if statements are supposed to throw certain errors when the value from the input match the if statment. but rather it is kind of giving a disjointed result. like when i typed in just 2 numbers, instead of throwing input is too low, i throws input is too high. and when i typed in numbers more than 5, it throws no error, and for the NaN no response from javascript.

is there anybody out there that can understand what am talking about? i think you should actually run the code yourselves and please educate me where am confuse.

pedroyanky
  • 323
  • 2
  • 10
  • 2
    `x == NaN` will not work use `isNaN()` – csharpfolk Jun 28 '16 at 10:26
  • thanks . but what about the other conditions, if <5, instead of throwing too low, it throws too high – pedroyanky Jun 28 '16 at 10:30
  • I tried this function and it works for me, can you add `console.log(x)` before `try` and post what it will write for you, and you are reading form normal `` form element? – csharpfolk Jun 28 '16 at 10:31
  • Look it works on JSFiddle: https://jsfiddle.net/s0pj18qo/, maybe some evil spirit redefined `Number` function? – csharpfolk Jun 28 '16 at 10:39
  • Hi @pedroyanky if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Adi Azarya Jun 29 '16 at 12:10

2 Answers2

0

you should use isNan() instead of Nan. see example here...

And extra context here: Why is IsNaN(x) different from x == NaN where x = NaN

Community
  • 1
  • 1
Adi Azarya
  • 4,015
  • 3
  • 18
  • 26
0

Try to debug in console:

NaN === NaN

And wonder :) Second, your mistake - you must to convert x to int:

x = parseInt(document.getElementById('formField').value);
Alexander Goncharov
  • 1,572
  • 17
  • 20