I was building a form the other day in Vue and I had to write number validation for the field so had to write the logic to check whether the input value is number or not. I wanted to list out the few ways I learnt which might be helpful to others.
NOTE: In JavaScript, special values like
NaN
,Infinity
and-Infinity
are numbers too - though, we'll be ignoring those values.
1) Using isNan()
The isNaN()
determines whether a value is NaN
or not. We can take advantage of this to determine whether a variable is number type or not.
var numberOfpushUpsToday = 34;
if(!isNaN(numberOfpushUpsToday)){
console.log('It is a number')
}
else {
console.log('It is not a number')
}
!isNaN(34) // returns true
!isNaN('34') // returns true
!isNaN('Hello') // returns false
!isNaN(true) // returns true
!isNaN(false) // returns true
!isNaN('undefined') // returns false
Limitations:
1) It returns true
for the Boolean values because the Boolean values are converted to numbers 0
and 1
accordingly so it would be misleading sometimes.
2) We have same issue for the null
value as well. It returns true and hence one has to be careful while writing the code.
2) Using typeof()
The typeof
operator returns a string indicating the type of the unevaluated operand.
num = 45
strng = '34'
typeof num // returns 'number'
typeof strng // returns "string"
typeof undefined // returns "undefined"
typeof null // returns "object"
If the variable is type number, it would return the string number
. We can use this to determine if the variable is number type.
var numberOfpushUpsToday = 34;
if(typeof numberOfpushUpsToday === 'number' ){
console.log('It is a number')
}
else {
console.log('It is not a number')
}
The typeof()
performs much better than isNaN()
. It correctly determines that a string variable, null and Boolean values are not numbers.
3) Using Number.isFinite()
The function isFinite()
determines if the passed value is finite. The arguments are first converted to numbers and then checks if the value is finite and hence this is the most best way among all the methods mentioned above.
Number.isFinite(34) // returns true
Number.isFinite('Hello') // returns false
Number.isFinite(undefined) // returns false
Number.isFinite(true) // returns false
Number.isFinite(null) // returns false
var numberOfpushUpsToday = 34;
if(Number.isFinite(numberOfpushUpsToday) ){
console.log('It is a number')
}
else {
console.log('It is not a number')
}
Conclusion:
Although these methods can get tricky with Boolean values, undefined
and null
, they are helpful in solving some problems in day to day life. One just have to be careful while writing the code according to their needs.
And that sums it up!!!
Thank you..
Comment below if you have any feedback or thoughts.
Top comments (7)
typeof is an operator, not a function, see developer.mozilla.org/en-US/docs/W...
Fixed it. Thanks.
This is clever.
What about adding:
Number.isNaN
dev.to/zombieleet/understand-the-d...
what about this.
typeof NaN // number