In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.
1. Using the isNaN() function
One of the most commonly used methods is to use the isNaN() function, which is a global function assigned to the JavaScript window object. However, you don't need to use the function like windows.isNaN(), just use the isNaN() function by itself.
The function will return false as long as the value we pass it is a number, and true otherwise. Here are some examples:
const myvalue = 4; isNaN(myvalue); // False isNaN('stringchain'); // True isNaN({}); // True isNaN(1.1); // False
As you can see, we can pass any kind of value to the function, be it primitive values or objects.
You can also execute conditional statements, like this:
const myvalue = 2;
if (!isNaN(valor)) {
console.log(This is a number');
}
2. Using the typeof function
The typeof function is used to find out what type a value is in JavaScript, returning 'number' if the value we pass it is a number. You can pass it a value directly:
typeof 2; // Return 'number'.
Or you can pass it a constant or a variable:
const myvalue = 2;
typeof myvalue; // Return 'number'.
You can also execute conditional statements, like this:
const myvalue = 2;
if (typeof myvalue === 'number') {
console.log('It's a number');
}