Skip to Content

3 Ways to Check if a Value is a Number in JavaScript

In this tutorial, we'll explore three different ways to check if a value is a number in JavaScript, using the isInteger(), typeof(), and isNaN() methods.

The isInteger() Method

The isInteger() method in JavaScript accepts a single parameter, the value being tested. The method returns true if the value is numeric, and false if it isn't:

Number.isInteger(123) - true
Number.isInteger(-123) - true
Number.isInteger("123") - false
Number.isInteger(4 / 2) - true
Number.isInteger(5 / 2) - false

The typeof() Operator

Another way to check if a value is a number is with the typeof() operator. Instead of providing a boolean response, the value's data type is returned:

typeof(123) - number
typeof(-123) - number
typeof("123") - string
typeof([123]) - object

You can also run a comparison by writing a conditional statement:

var value = 123;

if (typeof(value) === "number") {
// value is numeric
}

The isNaN() Global Variable

The final way we'll check if a value is a number is with isNaN(), a global variable that's assigned to the window object in the browser. Unlike the isInteger() method, if the return value is false, then our value is numeric. If true, then it's not numeric:

var value = 2;

isNaN(value) - false
isNaN("Hello") - true
isNaN({}) - true
isNaN(2) - false
isNaN(2.4) - false

Conclusion

This tutorial taught you three different ways to check if a value is a number in JavaScript.

Last Updated: September 03, 2022
Created: January 22, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.