Patrick Estabrook
Patrick Estabrook

Reputation: 125

use if (!num) to test typeof in javascript

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?

Upvotes: 3

Views: 282

Answers (4)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

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

Upvotes: 0

closure
closure

Reputation: 7452

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;  

}

Upvotes: 0

Daniel Buhai
Daniel Buhai

Reputation: 125

You could use the function: isNaN(value)

Upvotes: 0

I Hate Lazy
I Hate Lazy

Reputation: 48761

"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 !)

Upvotes: 3

Related Questions