First digit only counts in > prompt?

Can someone please help me understand why only the first digit is checked for greater than/less than in this code?

largerNumber = prompt( "Please enter a larger number:" );
smallerNumber = prompt( "Please enter a smaller number:" );

if (largerNumber < smallerNumber) {
alert( "Error: You entered a smaller number first." );

If I put in 300 for the largerNumber and 40 for the smallerNumber the alert goes off.


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


The input into the prompt comes in as strings, try to force the type to a Number before comparing them…

if (Number(largerNumber) < Number(smallerNumber))
1 Like

Thanks for all the tips and advice, will try the change!

Thanks again!

More precisely, it is enough to explicitly coerce only one of the inputs as JS will implicitly coerce the other because of the comparison operator between a number and a string, but must have at least one coerced other wise the comparison between a string and a string would be done alphabetically.

1 Like