-2

When I run this code through an html page in chrome, and put in, for example, number1 = 1000 and number2 gets 2000, it alerts 1000 is bigger. Why?

var number1 = prompt("Pick a number");
var number2 = prompt("Pick another number");

if (number1 < number2) {
    alert(number1 + "is bigger!");
} else if (number2 < number1) {
    alert(number2 + "is bigger!");
} else if (number1 == number2) {
    alert(number1 + "is equal to" + number2)
}
MattP
  • 489
  • 1
  • 7
  • 16
  • 1
    You're alerting the wrong messages `x < y` means `x is less than y` – Paul S. Nov 12 '15 at 16:24
  • @PaulS. That's *half* the problem, indeed. :-) – T.J. Crowder Nov 12 '15 at 16:25
  • I apologize, I had temporarily reversed the comparison symbols. They were originally: var number1 = prompt("Pick a number"); var number2 = prompt("Pick another number"); if (number1 > number2) { alert(number1 + "is bigger!"); } else if (number2 > number1) { alert(number2 + "is bigger!"); } else if (number1 == number2) { alert(number1 + "is equal to" + number2) } ... and it was still alerting backwards. – MattP Nov 12 '15 at 16:26
  • To check if number1 is bigger than number2 you need to wright it like this: number1 > number2 – Shhade Slman Nov 12 '15 at 16:29

1 Answers1

1

There are two problems above:

  1. Your messages are backward

  2. You're comparing strings, not numbers

You want to convert the result of prompt to number, and also correct which messages you're displaying.

You have several options for converting strings to numbers; I list your options and their plusses and minuses in this answer.

If you only fix #1 and not #2, you'll end up saying that "20" is less than "3", because comparing strings with < compares them lexigraphically, and "2" comes before "3" (the "0" in "20" never even gets looked at).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875