Reputation: 3168
I like to use the !!
in Javascript to ensure that a variable is set and that no error will be thrown.
However today I have a variable with 0
value that is valid for me. I need to ensure that it is not NaN nor undefined, is there really no short way to do it without the boring if (variable !== NaN && variable !== undefined
?
If that may help, I am using angular.
Thx.
Upvotes: 5
Views: 8978
Reputation: 662
const a = 'value';
if (isNaN(a) || a === null) {
console.log('a is NaN or null, undefined');
} else {
// business logic ;)
}
Handle null
in addition, because isNaN(null) === false
.
Upvotes: 6
Reputation: 1864
The correct way to check for undefined, null, NaN
is
if(a == null || Number.isNaN(a)) {
// we did it!
}
please notice the use of Number.isNaN
instead of just isNaN
.
If you did use just isNaN
then your check will not do what you want for values like strings or empty object
if(a == null || isNaN(a)) {
// {} comes in because `isNaN({})` is `true`
// strings that can't be coerced into numbers
// some other funny things
}
Read more at MDN
Upvotes: 2
Reputation: 1245
You can use isNan. It will return true
for undefined
and NAN
value but not for ZERO
.
const variable = undefined;
if(isNaN(variable)){
console.log('I am undefined / NAN');
}else{
console.log('I am something / zero');
}
Upvotes: 3