How to Check if a Value is a Number with JavaScript

In JavaScript, there are different ways to check whether a value is a number or something else.

The most common way is to use the typeof operator:

const value = 5

console.log(typeof value)
// "number"

One way you can use it in a practical context is to check if a form is filled out correctly, by using typeof in a conditional statement.

Let’s check if the value type of an input value is not a number value type, and then log out a message to the console:

const inputFieldAge = "10"
if (typeof inputFieldAge !== 'number') {
  console.log('This field has to be a number'

Because the inputFieldAge variable has a string assigned to it (the double quotes) instead of a number value type 10, the typeof operator will catch it.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on