-1

I'm learning JavaScript, and I'm trying to improve the code from an example from Beginning JavaScript. Specifically, I'm trying to get the code to check if an ending value is greater than the start value.

If I enter a starting value of 50 and an ending value of 6 or 8, then I get false for end <= start, even though both 6 and 8 are less than 50. If I enter any other value less than 50, I get true. I have the same problem with any starting value I've tested. I cannot find any error in the logic, so I must be misunderstanding the code (or just blind).

Thank you!

<body>
  <script>
    while (isNaN(start) == true) {
      var start = prompt("Enter starting value", "");
    }


    while (isNaN(end) || end <= start) {
      var end = prompt("Enter ending value", "");
      document.write((end <= start) + "<br/>");
      document.write(start + "<br/>");
      document.write(end + "<br/>");
    }
  </script>
</body>
Adam Schwartz
  • 61
  • 1
  • 10

3 Answers3

5

You are comparing string representations. You should use parseInt.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 2
    why don't you mark this as the duplicate it is instead of answering it? –  Feb 26 '16 at 19:15
  • 1
    Because then no question would ever get answered on this site because 99.99% of questions are just slight variations of another. So if we marked this as a duplicate then we would have to mark 99% of new questions as a duplicate and we might as well just shut down the site. – Dustin Poissant Feb 26 '16 at 19:19
  • Thank you. I tried to search for this question but I didn't know what search terms to use. – Adam Schwartz Feb 26 '16 at 20:34
0

Try this code:

<body>
  <script>
    while (isNaN(start) == true) {
      var start = prompt("Enter starting value", "");
    }


while (isNaN(end) || end <= start) {
  var end = prompt("Enter ending value", "");
  document.write((end.parseDouble <= start.parseDouble) + "<br/>");
  document.write(start + "<br/>");
  document.write(end + "<br/>");
}

Ethan JC Rubik
  • 174
  • 1
  • 1
  • 12
0

as you told u are newbie to Js hence i'll not mark your question down. But consider few things about this code which you've wrote:

  1. NaN shouldn't be used here for checking/validations
  2. NaN always return value NaN hence using for integer wouldn't be best practice at all.
  3. At last make following changes

    while (isNaN(start) == true) {
      var start = prompt("Enter starting value", "");
    }    
    
    while (isNaN(end) || (parseInt(end) <= parseInt(start))) {
      var end = prompt("Enter ending value", "");
      document.write((parseInt(end) <= parseInt(start)) + "<br/>");
      document.write(start + "<br/>");
      document.write(end + "<br/>");
    }
    

Thanks & Cheers :)

Amulya Kashyap
  • 2,333
  • 17
  • 25