How to check if a variable is a Number in JavaScript
In this tutorial, we are going to learn about two different ways to check if a given is a number in JavaScript.
typeof operator
The typeof operator will return the type of a given variable in string format, so that we can use it with if
conditional to check for a number.
Example:
let a = 11;
if (typeof a === 'number') {
console.log('a is number');
} else {
console.log('a is not a number');
}
Number.isInteger() method
The Number.isInteger()
method returns true if a provided variable is a number, otherwise it returns false.
let a = 11;
let b = "king";
if (Number.isInteger(a)) {
console.log('a is number');
} else {
console.log('a is not a number');
}
// it logs not a number
if (Number.isInteger(b)) {
console.log('b is number');
} else {
console.log('b is not a number');
}