Im a bit confused or maybe just a lack of knowledge. Just doing my first steps. My question is: I need to test when a number pair (like 100, 5 let’s say) will compare correctly as numbers and incorrectly as strings. How to fix it properly. I cant figure out the best way to test this last option.
1st test is Both numbers the same
2nd test is first number largest
3rd test is second number largest
I thought maybe I should say True to the first test. And say False when numbers as strings. ??
<script type="text/JavaScript">
alert(largest(false,false));
alert(largest(true,false));
alert(largest(false,true));
alert();
</script>
function largest (firstNum, secondNum) {
let largestNumber = largest;
firstNum = parseInt(prompt('Enter the first number: '));
secondNum = parseInt(prompt('Enter the second number: '));
if (firstNum == secondNum) { //3
return false; /// maybe True?.. see my question
} else {
if (firstNum > secondNum) { //1
return largest = firstNum;
} else if (firstNum < secondNum) { //2
return largest = secondNum;
}
if (isNaN(firstNum, secondNum)) { /// false if strings?
return false;
}
}
return largestNumber;
}
}
>Solution :
Your function is doing so many things as I can see
It’s returning true/false, largest number, etc.
I suggest you to clean up a bit your code like this!
function largest() {
const firstNum = parseInt(prompt('Enter the first number: '));
const secondNum = parseInt(prompt('Enter the second number: '));
if (isNaN(firstNum) || isNaN(secondNum)) {
alert('Invalid input!');
return null;
// return largest(); // This could work too
}
if (firstNum > secondNum) {
return firstNum;
}
return secondNum;
}
First, we ask the user to input both numbers
Then, we check if the values are valid, isNaN helps us with that, and if there is something incorrect, we show and alert and return
If the numbers are valid, we check
If firstNumber is larger than secondNumber, the largest one should be firstNumber
Otherwise, we return secondNumber (Last case)