-1

So I made a program which is able to check if you are old enough to drive based on the age you type. Here is the code:

const userAge = Number(prompt(`What is your age?`));

if (typeof userAge === NaN) {
    console.log('Error - please reload the page and type your age. ¯\_(ツ)_/¯');
} else {
    if (userAge >= 18) {
    console.log('You can start driving! ');
    } else {
        console.log(`Sorry - you'll have to wait a bit until you can drive. `)
    }
}

I was trying to handle the possibility of someone typing in a string of letters instead of a number, in which case the value of userAge would be NaN when something strange showed up. When I was checking if the value of userAge was NaN, it would return false even if it was NaN. I combed through the code to see if I had made a simple mistake, but I couldn't find anything. Would appreciate some help.

  • `typeof NaN` returns 'number'. Use `Number.isNaN(userAge)` – Yousaf May 17 '22 at 16:02
  • You need to use something like `isNan` (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#the_convenience_of_an_isnan_function) – msbit May 17 '22 at 16:02

1 Answers1

0

You should know that typeof NaN === 'number'. So if you want to check whether a variable is NaN, use the isNaN(variable) function.