Check if a value is a number in JavaScript
Question:
How to check if a value is a number in JavaScript? Answer:
const value = 100;
if (typeof value === 'number') {
console.log(`${value} is a number`);
}
Description:
There are multiple ways how you can check if a variable contains a number or not in JavaScript. The options are:
The typeof operator
The simplest way is to use the typeof
operator like this:
typeof value === 'number'
The isNaN method
With the built-in isNaN
method, you can check the opposite. This method returns true if the value is NOT a number.
isNaN(value);
The Number.isFinite, Number.isInteger
Using the isFinite
and isInteger
methods on the Number
object you can check if a value is a finite number or an integer:
Number.isFinite(value);
Check if a string contains a valid number
In the case of form submission, you get all values as strings. In such cases, the solutions above will not work. Instead, you can use the parseInt method and create a small helper function like this:
function isNumeric(str) {
return !isNaN(parseInt(str));
}
Reference:
JavaScript typeof reference
Share "How to check if a value is a number in JavaScript?"
Related snippets:
- Declare existing global variable in TypeScript
- Check if number is odd or even in JavaScript
- Convert Fahrenheit to Celsius in JavaScript
- Remove double quotes from a string in JavaScript
- Get class name of an object in JavaScript
- Convert milliseconds to minutes and seconds
- Check if an array contains a value
- Append an array to another in JavaScript
- Create HTML element with attributes in JavaScript
- Check if date is valid in JavaScript
- Check if a value is a number in JavaScript
- Check if a string is empty in JavaScript
- Check if string contains a substring in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get the first element of an array in JavaScript
- Convert Map values to array in JavaScript
- Escape quotes in JavaScript
- Get elements by data attribute in JavaScript
- Access JavaScript object property with space
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Access JavaScript object property with hyphen
- Add new Key - Value pair to an object in JavaScript
Tags:
value, variable, number, check, test, JavaScript Technical term:
Check if a value is a number in JavaScript