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!
Getting Started with Solid
Getting Started with Express
Create an RSS Reader in Node
Getting Started with Electron
Best Visual Studio Code Extensions for 2022
How to deploy a Node app using Docker
Getting Started with Sass
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Getting Started with Vuex: Managing State in Vue
Using Axios to Pull Data from a REST API
