Greater than something bug in Js

Viewed 67

I am getting a weird bug where in my game, where you enter a guess that is greater than the maxNum like 8 as the guess and the maxNum entered is 10. The game is supposedly think 8 is greater than 10. The issue with the code is coming from the checkGuess function. I have no idea if it is cause I am using global variables.

1 Answers

The value you get from input value is always a String (text). In order to get a proper number, please use parseInt if you expect integers, or parseFloat for floating point numbers.

For your specific case, the code could look like this:

maxNum = parseInt(document.getElementById('maxGuessRange').value, 10);

Please be aware to always set the number base parameter explicitly (10 in this example means decimal) because the default behavior, when no parameter is given, is unsafe and can be easily confused with octal and other number systems.

The bug comes from the code like this, which results in true when strings are compared instead of numbers:

'10' < '8'

Please always parse user input to proper number types to avoid unexpected coercions.

Related