I'm learning JS recently and doing some exercises. I got stuck in this one because I can't make sense of what happens to me. The following code works perfectly for me except when the 1st number that I enter is 15 and the second is 2... The alert jumps to me "There are a total of 0 even numbers between the two selected numbers"
What am I wrong?
<script>
var numero1 = prompt("Facilíteme el primer número");
var numero2 = prompt("Facilíteme el segundo número");
var total = 0;
if(numero1 < numero2){
var chico = numero1;
var grande = numero2;
}
if(numero2 < numero1){
var chico = numero2;
var grande = numero1;
}
var tipo = (chico%2) ? "Impar" : "Par";
console.log(chico);
if(tipo == "Par"){
while(chico < grande){
document.write(total);
total = total + 1;
chico = parseInt(chico) + 2;
}
}else{
while(grande > chico){
//document.write(total);
total = total + 1;
grande = parseInt(grande) - 2;
console.log(chico);
}
}
alert(`Hay un total de ${total - 1} números pares entre los dos números seleccionados`);
</script>
The user input is a string. If the user types 2 and 15, you'll get that
numero1
is the string"2"
andnumero2
is the string"15"
.When you compare
numero1<numero2
, strings are being compared, and they are done in "alphabetical order". Therefore"15"
it will be less than"2"
, because in a dictionary it would appear before (since it is the first "letter", which is"1"
, before"2"
).From there it is not surprising that you get surprising results. You should convert them to integer with
parseInt()
as soon as you read them withprompt()
, for example like this: