Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this if statement not recognise numbers?

This code works fine on letters, returning if the letters are upper or lower case but it always returns the number as "6 is a uppercaseletter"

let userLetter = prompt("Please enter an uppercase, lowercase letter or a number");


if (typeof userLetter === 'number') {
    userLetter = userNumber;
    alert(`${userNumber} is a number`);
} else if (userLetter.toUpperCase() === userLetter) {
    alert(`${userLetter} is a uppercase letter`);
} else if (userLetter.toLowerCase() === userLetter) {
    alert(`${userLetter} is a lowercase letter`);
} else {
    alert('Something went wrong');
}
 

I expected the typeof operator would recognise that the input is a number but it doesn’t. When a number is entered it always returns the uppercase option.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

prompt always returns a string (for which typeof returns "string").

You could use isNaN instead.

if (!isNaN(userLetter)) alert(`${userLetter} is a number`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading