avatarDr. Derek Austin 🥳

Summary

The provided content discusses various methods for checking if a value is a number in JavaScript, emphasizing the nuances of handling NaN, Infinity, and integers within the language's dynamic typing system.

Abstract

The article delves into the intricacies of number validation in JavaScript, highlighting the limitations of the typeof operator when dealing with special numeric values like NaN and Infinity. It suggests creating a custom isNumber() function to more accurately determine if a value is a finite number, avoiding the pitfalls of JavaScript's dynamic typing. The author also introduces the built-in Number.isFinite() method as a more straightforward solution for checking finite numbers without type coercion. Additionally, the article touches on integer validation, parsing numbers from strings, and handling monetary values with regular expressions. The piece concludes by clarifying that JavaScript treats all numbers as floating-point values, with BigInt available for larger integers, and recommends resources for further reading on the topic.

Opinions

  • The author believes that using typeof alone is insufficient for number validation due to its treatment of NaN and Infinity as numbers.
  • A robust custom isNumber() function is recommended for precise number checks, indicating a preference for explicit validation over relying on JavaScript's built-in behaviors.
  • The Number.isFinite() method is favored for its simplicity and reliability in checking for finite numbers without type coercion.
  • The author suggests that developers should be aware of JavaScript's number representation as 64-bit floating points and the distinction between Number and BigInt types.
  • Regular expressions are proposed as a tool for parsing monetary values, reflecting a practical approach to dealing with currency symbols and formatting in number strings.
  • The article promotes further learning on the subject, providing links to additional resources and related articles, showcasing an educational intent to empower readers with comprehensive knowledge.

How to check for a number in JavaScript

Numbers are a primitive type in JavaScript, but just using typeof will not differentiate numbers from NaN or Infinity.

Photo by Alex Chambers on Unsplash

It is useful to know how to check if a value is of the primitive type number, since JavaScript is a dynamically typed language.

The easiest way to check for a number is using typeof, which will return the string "number" for any value of the number primitive type, including NaN, Infinity, and -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 typeof.

Photo by Samuel Zeller on Unsplash

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 — because NaN values are considered numbers in JavaScript.

Photo by Gemma Evans on Unsplash

When the typeof keyword returns “number”

An obvious solution to check for the number primitive type is to use the typeof keyword, as I showed above.

But typeof is an incomplete solution, because of two special values in JavaScript: NaN (“Not a Number”) and Infinity.

For my currency example, I know I have a bug if my monetary value is NaN or Infinity, but 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 NaN:

Photo by Timo Kaiser on Unsplash

A custom isNumber() function

Arobust, custom isNumber() function would use typeof to check for the primitive type, check for NaN values, and check for Infinity:

Or, in the case where one is confident that NaN and Infinity are not going to come up, just checking that typeof==="number" would be enough.

Photo by 🇨🇭 Claudio Schwarz | @purzlbaum on Unsplash

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.

Here is the one-liner for how to check for a number in JavaScript:

But, there is a better way to check for a finite number in JavaScript — the helper function Number.isFinite() has the same behavior as the custom isNumber() function I wrote. I include an example in the next section.

Photo by Bernard Hermant on Unsplash

The easiest way to check for a number: Number.isFinite()

It is actually unnecessary to write custom functions to check for a number, though it is an instructive way to remember that the JavaScript values Infinity, -Infinity, and NaN are all of the number primitive type.

“The Number.isFinite() method determines whether the passed value is a finite number.” — MDN Docs

The Number.isFinite() method will return true for finite numbers, and false for Infinity, -Infinity, and NaN — exactly what we want:

There is also the global isFinite() function, which will perform type coercion (such as coercing strings to numbers), as shown above.

I discuss these methods in depth in my article on Infinity in The Startup:

Photo by Bogomil Mihaylov on Unsplash

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.

The following code snippet gives an example of how to check for an integer:

Using typeof would differentiate a string that is being coerced into a number from an actual number, as would the strict equality operator ===.

Photo by Markus Spiske on Unsplash

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.

Thoroughly parsing money using regular expressions in JavaScript is beyond the scope of this article, but this code removes $ and , before parsing:

Note that the global functions parseInt() and parseFloat() will coerce values to strings, if necessary, and will return NaN if coercion fails.

There are also the functions Numbers.parseInt() and Number.parseFloat(), which have the same exact behavior.

According to the MDN Docs, those duplicate functions were added to ECMAScript 2015 for the “purpose [of] modularization of globals.”

Photo by Toa Heftiba on Unsplash

Does JavaScript actually have separate integers?

No, JavaScript only has one type of number, which is represented internally as a 64-bit floating point representation.

That floating point is the primitive data type number, and there is also a type called BigInt that can be used for arbitrarily large numbers.

The global functions parseInt() and parseFloat() differ in what they expect and will output, but not because there are actually separate integer and floating point types in JavaScript.

Photo by Volkan Olmez on Unsplash

Conclusion

Checking for a number in JavaScript is not particularly complicated — typeof works basically how it should, as long as one is aware that both NaN and Infinity have the typeof number.

The easiest way to check for a finite number (i.e. not NaN or Infinity) in JavaScript is using Number.isFinite(), which does not coerce values to numbers, or the global isFinite(), which does perform type coercion.

Checking for an integer specifically involves using the parseInt() function, followed by comparing the parsed value to itself using >== (which will type coerce non-number values, such as strings to numbers) or === (which will only return true if both values are numbers).

Under the hood, integers and floats are all the same: JavaScript only has one type of number, the number primitive type.

Photo by K. Mitch Hodge on Unsplash

Further reading

  • The regular expression ^[0–9]+(\.[0–9]{1,2})?$ matches money:
Photo by Alejandro Ortiz on Unsplash

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

Programming
JavaScript
Software Engineering
Coding
Web Development
Recommended from ReadMedium