There are multiple ways to can check if a given variable (var) is a number or not in JavaScript. Let us take a look at a few of them with examples.
Example 1: Using typeof operator
var variable = 22.5;
if (typeof variable === 'number') {
console.log('The variable is a number!');
} else {
console.log('The variable is not a number!');
}
Output:
Example 2: Using Number.isNaN()
var variable = "hello";
if (!Number.isNaN(variable)) {
console.log('The variable is a number!');
} else {
console.log('The variable is not a number!');
}
Example 3: Using Regular Expression
var variable = 100;
const regexStr = "/^-?\d+(\.\d+)?$/";
if (regexStr.test(variable)) {
console.log('The variable is a number.');
} else {
console.log('The variable is not a number.');
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!