0

I have this javascript code that is working mostly as intended. It is two functions, the first prompts the user for two values on a button press, and the second compares them and displays an output on another button press.

It works almost perfectly, except the outputs don't make sense. It is supposed to output 'true' if inpOne is greater than inpTwo, and 'false' otherwise.

If both inputted numbers are less than 10 i.e. inpOne = 8, inpTwo = 1, it will output true, as it should. However, if inpOne = 20, and inpTwo = 3, it outputs 'false' which is incorrect. I've tried with many other values and it seems to be random to some extent... Can someone look over my code and tell me what I'm doing wrong? Thanks!

Edit: I realize it is three functions, the last function just displays the results to an HTML element...

let inpOne;
let inpTwo;

function promptForCompare() {
    inpOne = prompt('Enter first number','');
    inpTwo = prompt('Enter second number','');
}

function checkIfGreater() {
    let valComp = inpOne > inpTwo ? true : false;
    return displayResult(valComp), console.log(valComp);
}

function displayResult(input) {
    if (input == true) {
        document.getElementById("resDisp").innerHTML = "Number is greater!";
    } else {
        document.getElementById("resDisp").innerHTML = "Number is NOT greater!";
    }
}
  • Since inputs are Strings you need to parse the value you receive from prompt to integers. – Dor Ben Itzhak May 30 '21 at 05:53
  • Your issue is that `prompt` returns a string, even if the user enters a number, so your comparison is checking whether the string `'21' < '3'`, which is true. I have no idea why someone closed your question as a dupe of an unrelated question that happens to have the same answer, but welcome to SO I guess. – fenomas May 30 '21 at 05:54
  • I knew it had to be something simple... I added Number() to the prompt and it now works as intended every time... To clarify, as a string, '21' is less than '3' because it starts with '2', correct? – NickLeylandMedia May 30 '21 at 05:57
  • This is true. Number(), parseInt(), or just add '+' before the prompt will do the job. – Dor Ben Itzhak May 30 '21 at 05:58

0 Answers0