Typescript: test for Nan, null and undefined only

Viewed 3062

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.

3 Answers

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');
}
let a = 'value';
if (isNaN(a) || a == null) {
    console.log('a is NaN or null, undefined');
} else {
    // business logic ;)
}

To handle null also, caz isNaN(null) // false

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

Related