How to check if Variable is a number in JavaScript

Updated onbyAlan Morel
How to check if Variable is a number in JavaScript

Table of Contents

  1. isNaN()
  2. typeof
  3. Conclusion

It is a common occurrence to need to check if the value of a variable is a number or not in JavaScript. Because JavaScript is not a statically typed language, it is sometimes not clear what type of value a variable is.

In this post, we'll learn the different ways to check if a value is a number.

isNaN()

The best way to check if a value is a number is to use the isNaN() method.

The isNaN() is a built-in function that returns true if the value passed to it is not a number.

Let's look at an example of isNaN():

JAVASCRIPT
const variable = 3; isNaN(variable); // false isNaN(3.5); // false isNaN("hello world"); // true isNaN(undefined); // true

Because isNaN() returns true if the value passed to it is not a number, if it returns false, then it means that the value is a number.

You can encapsulate this into a function to make it more readable:

JAVASCRIPT
const isANumber = (value) => !isNaN(value); isANumber(3); // true isANumber(3.5); // true isANumber("hello world"); // false isANumber(undefined); // false

typeof

Another way to check if a value is a number is to use the typeof operator.

The typeof operator returns a string that represents the type of the value passed to it. Therefore, if the variable is a number, the typeof operator will return number.

JAVASCRIPT
const variable = 3; typeof variable; // number typeof 3.5; // number typeof "hello world"; // string typeof undefined; // undefined

Using that information, you can just do a simple string comparison to check if the value is a number.

JAVASCRIPT
const variable = 3; typeof variable === "number"; // true typeof 3.5 === "number"; // true typeof "hello world" === "number"; // false typeof undefined === "number"; // false

You can also encapsulate this into a function to make it more readable:

JAVASCRIPT
const variable = 3; const isNumber = (value) => typeof value === "number"; isNumber(variable); // true isNumber(3.5); // true isNumber("hello world"); // false isNumber(undefined); // false

Conclusion

There you have it, the two best ways to check if a value is a number in JavaScript.

Hopefully, you've found the examples and functions useful to you.

Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.