0

I was trying to make a comparison between num1 and num2:

<form>

    <input placehoder="num1" type="text" id="num1"/>

    <input placehoder="num1" type="text" id="num2"/>

    <button type="button" id="comparar">Compara</button>

</form>

The issue is that until I found out that to declare that the inputs are going to be numbers with the comands let num1 = parseInt(document.getElementById("num1").value); the systme worked but sometimes it did not show the correct alert.

let compare = document.getElementById("comparar");



function comparator(){
    let num1 = parseInt(document.getElementById("num1").value);
    let num2 = parseInt(document.getElementById("num2").value);
    if ( num1 > num2){

            alert('num1 higher');

    }else if(num1 == num2){
        alert('are equal');
    }

    else{
        alert('num2 higher')
    }
}


compare.addEventListener('click', comparator);

Does anyone knows why when not using parseInt to compare two numbers it show random results?, basiccally what is it comparing?.

thanks

Isma
  • 14,604
  • 5
  • 37
  • 51
Joaquin86
  • 86
  • 9
  • 3
    Without `parseInt` you'd compare strings, the result is not random, though. – Teemu Apr 25 '20 at 15:18
  • 1
    [Javascript string/integer comparisons](https://stackoverflow.com/questions/5630123/javascript-string-integer-comparisons) – palaѕн Apr 25 '20 at 15:19

4 Answers4

2

You should validate the number1 and number2 before compare, or set type="number" for inputs

Example parseInt("1a") return 1

If you input 1a and 1, it show equal.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
1

Without parseInt you are comparing two "string" and not two "int".

It's not random, it takes the number in order 1, 2, 3, ... and you will have results like : "2" > "10" ==> true

0

The inputs in your form are string objects. Calling parsInt on a string object comprised of digits will convert it into number object.

You can use the typeof method to check types. Like this:

var num1 = "1"
var num2 = 1

console.log(typeof(num1)) // Output -> string
console.log(typeof(num2)) // Output -> number

In this example, num1 is a string object while num2 is a number object, even though they have the same digit.

jws1
  • 111
  • 1
  • 4
0

Without using parseInt you would compare two strings. In JavaScript strings are compare with first letter alphabetically , for example : "banana" > "apple" will return true. If the first letters are equal , then it compares second letters and so on. Capital letters have priority over small letters.