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
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript