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 variable is a number in JavaScript.
Using typeof operator
To check if a variable is a number, we can use the typeof operator in JavaScript.
The typeof
operator returns the type of a given variable in string format.
Example:
let a = 11;
if (typeof a === 'number') {
console.log('variable is a number');
} else {
console.log('variable is not a number');
}
Output:
"variable is a number"
Using Number.isInteger() method
Similarly, we can also use the Number.isInteger() method in JavaScript to check if a variable is a Number or not.
The Number.isInteger()
method returns true if a provided variable is a number, otherwise it returns false.
Here is an exmaple:
let a = 11;
let b = "king";
if (Number.isInteger(a)) {
console.log('a is number');
} else {
console.log('a is not a number');
}
False case:
let a = 11;
let b = "king";
// it logs not a number
if (Number.isInteger(b)) {
console.log('b is number');
} else {
console.log('b is not a number');
}