Skip to content

Why does my program think that 72 is larger than 500?

I’m trying to make a program that takes three numbers from the user and gives them the biggest and smallest, but sometimes the numbers are flipped (The biggest is switched with the smallest), and sometimes some numbers just get left out. Can anyone tell me what is happening?

const testArray = [
  prompt(`Pick a number`),
  prompt(`Pick a number`),
  prompt(`Pick a number`),
];

let max = testArray[0];
let min = testArray[0];

for (let i = 1; i < testArray.length; i++) {
  if (testArray[i] > max) max = testArray[i];
  if (testArray[i] < min) min = testArray[i];
}

console.log(`The biggest number you chose was ${max}`);
console.log(`The smallest number you chose was ${min}.`);

Somehow the numbers get flipped, or some numbers get left out.

Answer

Why does your program think 72 is larger than 500?

Because –

  1. You are comparing between the strings "72" and "500", not between the numbers 72 and 500
  2. From the string comparison perspective “72” is greater than “500”

You can verify this with the following code –

// user inputs - 72, 123, 500
console.log(testArray);     // output: ["72", "123", "500"]
console.log("72">"500");    // output: true

How did this happen?

User inputs taken with prompt() are always read as strings.

How do you fix it?

As others have already mentioned, before comparing you have to convert the strings to numbers. You can do this while taking the inputs, like –

const testArray = [
  Number(prompt(`Pick a number`)),
  Number(prompt(`Pick a number`)),
  Number(prompt(`Pick a number`)),
];