Can prompt() Evaluate Numbers Wrong?

Hello people,

I have a question. I am trying to write a program which writes the greater number to the console. I am facing a problem when i enter one of the number single and the other double digit.

If i enter first number single digit, let’s say 5. When i enter the second number two digits but the first digit of that number should be less than the single digit number(first number), let’s say 39,

“Greater number: 5” is what i see in my console.

I believe it has something to do with prompt().

What is the problem here?

Example:
Input:
First number: 5
Second number: 39

Output:
“Greater number : 5”

var a = prompt("Enter the first number."); 
var b = prompt("Enter the second number."); 
console.log("First number: " + a);
console.log("Second number: " + b);

if(a > b){
    console.log("Greater number: " + a); 
}
else if(b > a){
    console.log("Greater number: " + b);
}
else{
    console.log("Two numbers are equal.");
}   

What type of value does prompt() return?
If it’s not a number than the comparison might be different than what’s expected. Perhaps a check is in order?

console.log(typeof(a));
2 Likes

The return value of prompt is always a string, unless the user clicks Cancel , in which that case it returns null .

1 Like

For anyone having the same problem, the thing that i was looking for was parseInt();

parseInt() → Turns a string to a number.

Example:

var a = parseInt(prompt(“Enter the first number.”));
var b = parseInt(prompt(“Enter the second number.”));