How to check if a variable is a number in JavaScript
In this tutorial, we are going to learn about how to check if a variable (including a string) is a number in JavaScript.
JavaScript has a built-in isNan()
function where it returns false
if a given variable is a number else it returns true
if a given variable is not a number.
Example:
const num = 3;
console.log(isNaN(num)); // false
const strNum = '3';
console.log(isNaN(strNum)); // false
const str = 'react';
console.log(isNaN(str)); // true
In the above code, we are getting false
if a variable has a value string number '3'
, But we need true
to do this we need to create our own function called isNumeric
.
function isNumeric(num){
return !isNaN(num); // added negation operator
}
console.log(isNumeric('3')); // true
console.log(isNumeric(3)); // true
console.log(isNumeric('fabric')) // false