- Instant help with your JavaScript coding problems

Check if a value is a number in JavaScript

Question:
How to check if a value is a number in JavaScript?
Answer:
const value = 100;

if (typeof value === 'number') {
    console.log(`${value} is a number`);
}
Description:

There are multiple ways how you can check if a variable contains a number or not in JavaScript. The options are:

The typeof operator

The simplest way is to use the typeof operator like this:

typeof value === 'number'

The isNaN method

With the built-in isNaN method, you can check the opposite. This method returns true if the value is NOT a number.

isNaN(value);

The Number.isFinite, Number.isInteger

Using the isFinite and isInteger methods on the Number object you can check if a value is a finite number or an integer:

Number.isFinite(value);

Check if a string contains a valid number

In the case of form submission, you get all values as strings. In such cases, the solutions above will not work. Instead, you can use the parseInt method and create a small helper function like this:

function isNumeric(str) {
  return !isNaN(parseInt(str));
}

 

Share "How to check if a value is a number in JavaScript?"