Deciding whether something is a number in JavaScript should be a straightforward type check (i.e., using the isNaN() function), but, as it turns out, it is a bit more tricky.
How to Determine Whether or Not Something is a Number in JavaScript
This is due to JavaScript’s forced conversion-to-number behavior. The often used methods, isNaN() and isFinite() can have confusing behavior and return incorrect answers.
Thankfully, ECMAScript 6 (JS language specification) was released with the intention of fixing these issues with Number.isNaN() and Number.isFinite(), along with making many other language clarifications and improvements.
Use the isNumeric() Function
Until that JS language version is the standard and used in browsers, we will need to be careful when checking if a value is a number.
The jQuery project has a tiny isNumeric() function implementation that fixes this odd JS behavior. There are some other implementations, but many of those fail in some of the JS type-casting-gotcha corner cases.
The isNumeric() function below is usable in your own code, even without jQuery.
var isNumeric = function(obj){ return !Array.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }
isNumeric() Examples
Below are some examples of using isNumeric() with its boolean output:
isNumeric(10); // true isNumeric(“0.75”); // true isNumeric(“123e–2”); // true isNumeric(–0xFFF); // true isNumeric(Infinity); // false , use isFinite() isNumeric(NaN); // false , use isNaN() isNumeric([1]); // false isNumeric(true); // false isNumeric(“foo”); // false isNumeric(null); // false isNumeric(new Date()); // false
HostingAdvice.com is a free online resource that offers valuable content and comparison services to users. To keep this resource 100% free, we receive compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). HostingAdvice.com does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.
Our site is committed to publishing independent, accurate content guided by strict editorial guidelines. Before articles and reviews are published on our site, they undergo a thorough review process performed by a team of independent editors and subject-matter experts to ensure the content’s accuracy, timeliness, and impartiality. Our editorial team is separate and independent of our site’s advertisers, and the opinions they express on our site are their own. To read more about our team members and their editorial backgrounds, please visit our site’s About page.