Top 4 ways to check if a value is a Number in JavaScript

Written by Maxime
Updated on May 17, 2023
2 mins read
check if the value is a number in javascript

You can use several methods to check if a value is a number in JavaScript.

Here are four best ways to check: 

typeof operator:

The typeof operator returns a string indicating the type of the value. If it returns 'number', then the value is a number.

check value is a number in javascript using typeof
function isNumber(value) {
  return typeof value === 'number';
}

isNaN() Global function:

The isNaN() function checks whether a value is NaN (Not-a-Number). By using the negation operator (!), you can determine if the value is a valid number.

check value is a number in javascript using isNaN
function isNumber(value) {
  return !isNaN(value);
}

Number.isFinite() method:

The Number.isFinite() method checks if a value is a finite number. It returns true for finite numbers and false for NaN, Infinity, or -Infinity.

check value is a number in javascript using isFinite
function isNumber(value) {
  return Number.isFinite(value);
}

Regular expressions:

This approach uses a regular expression to check if the value matches the pattern of a number. It allows an optional sign (+/-) at the beginning and supports decimal numbers.

check value is a number in javascript regular expressions
function isNumber(value) {
  return /^[+-]?\d+(\.\d+)?$/.test(value);
}

You can choose the method that suits your requirements and the specific context of your code.

Here is another quick guide about formatting dates in JavaScript.

Project Based Tutorials
Tips & Tricks
Modern Technologies
Real-World Challenges
Creative Content
Build-Apps from Scratch
Web Development Content
17+ Videos Published
Coder Champ © 2023 - 
Privacy Policy
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram