Check if String Is a Number or Not in JavaScript

In this article will be on how to check if a given value is a number or NaN (Not-a-number).

In programming language, a number is a datatype that denotes a integer or a floating point. And a String can be define as a sequence of character which includes both letters and numbers. Example: "Hello", "123abc" etc.

So let's check how we can find if a string consist only number using the method below:

Using isNaN() to check if a JavaScript String has a Number.

The isNaN() function determine whether a given value is a number or NaN (Not-a-Number).

If the output returns true, that means it's NaN value and if it's false, it's a valid number.




console.log(isNaN('2022'))  // false
console.log(isNaN('computer')) // true
console.log(isNaN('123abc')) // true

We can write a function isNumber() that will return true if the string is a number.

function isNumber(val){
  if(isNaN(val)) {
    return false
    return true
console.log(isNumber('2022'));  // true         
console.log(isNumber('computer')); // false       
console.log(isNumber('123abc')); //false

Using Number() function to check if a string is a number

The Number() function convert a given value of other datatype (eg: string etc) to a number representing the object 's value.


new Number(value)

It will return number if the string contains only number or else it will return NaN (Not-a-Number).


console.log(Number('2022')) // true
console.log(Number('hello')) //NaN
console.log(Number('123abc')) //NaN

Using Unary Plus (+) operation to determine whether a string is numeric in JavaScript

The + operator coverts a string to a number. It will return the number value of the string or else it will return NaN (Not-a-Number) if the given value is not a pure number.


console.log(+'2022') // 2022
console.log(+'hello') // NaN
console.log(+'abc123') //NaN

Related Topics:

Check If A String Contains A Substring In Javascript

Check If String Is Empty In JavaScript

Check if a value is a number in JavaScript

How to compare two strings in JavaScript?

How To Check Null Values In JavaScript?

💾 Recommended Articles