This post will discuss how to check if a variable is a numeric in JavaScript/jQuery. That is, find out if a variable represents a valid number or not.

1. Using jQuery library

The jQuery $.isNumeric() function checks whether a given value represents a valid numeric value or not. It returns true if the value is of type number or string and can be coerced into finite numbers, and false otherwise. It takes the value to be tested, which can be of any type, such as a string, a number, a boolean, or an object. The function will try to convert the value to a number and then check if it is finite. If the value is not a valid number, it will return NaN (Not a number), which is considered false by the function. Here are some examples of using the jQuery isNumeric() function with different values:

Download Code

2. Using typeof operator

In JavaScript, we can use the typeof operator, which returns a string indicating the operand’s type. We can use the typeof operator with a strict equality operator (===) to check for primitive numeric values. To check for the Number object as well, we can use the instanceof operator. Here are some examples of using the typeof() and instanceof operator on different inputs:

Download  Run Code

 
The above solution returns true for +Infinity, -Infinity, and NaN. This also does not work with strings, which can be coerced into finite numbers (e.g. "1"). To handle this, we can place some additional conditions using isFinite() and isNaN() functions. The following code illustrates this:

Download  Run Code

 
Alternatively, we can check for numeric values using the unary plus operator (+). This operator also has same limitations as the typeof operator. That is, it doesn’t work for the Number object, and consider +Infinity and -Infinity as numbers. Also, it doesn’t handle strings that can be coerced into finite numbers. These limitations can be handled in the same way as the previous solution.

3. Using Number.isFinite() function

Finally, we can use the Number.isFinite() function, which determines whether the specified value is a finite number. It returns true for finite numbers, and false for NaN, positive Infinity, negative Infinity, or non-numeric values including strings that can be coerced into finite numbers. Here are some examples of using the Number.isFinite() function with different values:

Download  Run Code

That’s all about checking if a variable is a numeric in JavaScript/jQuery.