typeof will not differentiate numbers from NaN or Infinity.
One example when a number might show up as another type, indicating a bug in my code, would be in parsing currency.
In this case, I would know that I forgot to parse the string into a number when I get the value of “
string” back from
Catching a failed parse
If I use parseFloat() to check the currency value, but I forgot to strip the currency symbol, I get a failed parse and an odd result:
Oh, no. In this case, it looks like
typeof is not working how I expected.
typeof keyword returns “number”
An obvious solution to check for the number primitive type is to use the
typeof keyword, as I showed above.
For my currency example, I know I have a bug if my monetary value is
typeof returns “
number” for both these values.
Perhaps my input was written using a currency symbol, and I simply tried to use
parseFloat() to capture the value. That would result in
A more robust
isNumber() function would check for NaN values, check for Infinite values, and use
typeof to check for the number type:
Or, in the case where one is confident that NaN and Infinity are not going to come up, just checking that
typeof==="number" is enough.
The one liner
I love one-liners. I think they need to be documented with comments, but I think they are actually really useful, not just fancy.
Check if a variable is an integer
To check if variable A is an integer I could use the loose equality operator
== to see if the parsed value equals itself.
That would look like the following code example:
typeof would differentiate a string that is being coerced into a number from an actual number, if that is important to you.
Strip out currency symbols
For a better, more robust function, I might want to strip out currency symbols (such as the dollar sign and any commas) first.
, before parsing:
Infinity have the
Checking for an integer specifically involves the
- The function
Number.isInteger()does not coerce strings to numbers:
The Number.isInteger() method determines whether the passed value is an integer. Number.isInteger(value) The value to…
- The regular expression