How to check if Variable is a number in JavaScript
Table of Contents
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()
:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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
.
JAVASCRIPTconst 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.
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React