3

I'm writing a function that needs to test if the argument passed is a number. I'm a novice so I just wrote something like this:

if (typeof num !== "number") {
    return false;
}

I looked at someone else's code for the same purpose and they just had something like this:

if (!num) {
    return false;
}

I find this confusing. If zero was passed to the function, wouldn't !num evaluate as true? How does this second chunk of code robustly test the type of the num argument?

4 Answers 4

3

"If zero was passed to the function, wouldn't !num evaluate as true?"

Yes it would, and also if NaN or any falsey non-number value.

"How does this second chunk of code robustly test the type of the num argument?"

It doesn't. It only tests the "falseyness" of the value. Every falsey value will give a true result to the if statement.

Those values are:

  • false
  • ""
  • 0
  • NaN
  • null
  • undefined

Any other value will fail the if condition.

(Of course all this is reversed if you don't negate the value with !)

Sign up to request clarification or add additional context in comments.

Comments

0

You could use the function: isNaN(value)

Comments

0

You are right about the second statement not validating properly whether the input is number or not. You might as well improve you check like this:

if ((typeof(num) !== "number) || (isNaN(num) || (!isFinite(num) {

    return false;  

}

Comments

0

You are correct that is not a valid line of code. Here Is Test Correct code would be:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

as describe in This ANSWER

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.