Site icon codippa

How to check if a value is number in javascript

It is often required to check the type of a value before performing some operation. Example, it would be better to check if the value of a variable is number before adding another number to it.
This article will explain different ways in which you can check if a value is a number or not.

number is a generic type in javascript. It means a value may be an integer(such as 10, 56, 1099 etc.) or a decimal(such as 10.99, 54.3232 etc.), it does not tell you the specific type of the value.

Method 1: Using typeof operator

Javascript typeof operator is followed by a value or a variable and returns the type of that value or the value contained in a variable.
For numeric data types, it returns ‘number’. By comparing the return value of typeof with ‘number’, it is possible to check if a value is numeric or not. Example,


Note that with this method you can not tell whether the value is an integer or a decimal.

Method 2: Using Number.isInteger()

Number object provides an isInteger method which accepts a single argument and returns true if the type of the argument is an integer, false it is of any other type(such as a string, decimal, object etc.).
This method can only check for integers and not for decimal values, that is, for decimal values, this method will return false. Example,


Method 3: Using isNaN function

isNaN function accepts a single argument and returns true if the type of argument is a number(integer or decimal), false if it is of any other type(string, array, object etc.) where NaN stands for Not a Number. Example,


Note that all the methods in this article check if a value is numeric or not, the do not convert a string to number.
Hope you liked this post, why not click the clap icon.

Exit mobile version